0
# Core Download API
1
2
The YoutubeDL class is the central interface for all download and extraction operations. It manages configuration, coordinates extractors and post-processors, handles progress reporting, and provides comprehensive download functionality.
3
4
## Capabilities
5
6
### YoutubeDL Class
7
8
The main API class that handles downloads, extraction, and coordination of all yt-dlp functionality.
9
10
```python { .api }
11
class YoutubeDL:
12
"""
13
Main yt-dlp class for downloading and extracting video information.
14
15
Manages configuration, coordinates extractors and post-processors,
16
handles progress reporting, and provides comprehensive download functionality.
17
"""
18
19
def __init__(self, params=None, auto_init=True):
20
"""
21
Initialize YoutubeDL instance.
22
23
Parameters:
24
- params: dict, configuration options (see YDLOptions type)
25
- auto_init: bool, whether to initialize automatically
26
"""
27
28
def __enter__(self):
29
"""Context manager entry."""
30
31
def __exit__(self, exc_type, exc_val, exc_tb):
32
"""Context manager exit."""
33
34
def close(self):
35
"""Clean up resources and close connections."""
36
```
37
38
### Download Operations
39
40
Primary methods for downloading content from URLs with various configuration options.
41
42
```python { .api }
43
def download(self, url_list):
44
"""
45
Download from a list of URLs.
46
47
Parameters:
48
- url_list: list[str], URLs to download
49
50
Returns:
51
int: Exit code (0 for success, non-zero for errors)
52
"""
53
54
def download_with_info_file(self, info_filename):
55
"""
56
Download using information from a saved info file.
57
58
Parameters:
59
- info_filename: str, path to info file
60
61
Returns:
62
int: exit code
63
"""
64
```
65
66
### Information Extraction
67
68
Methods for extracting metadata and processing information without necessarily downloading files.
69
70
```python { .api }
71
def extract_info(self, url, download=True, ie_key=None, extra_info=None, process=True, force_generic_extractor=False):
72
"""
73
Extract information from URL and optionally download.
74
75
Parameters:
76
- url: str, URL to extract from
77
- download: bool, whether to download files
78
- ie_key: str|None, specific extractor to use
79
- extra_info: dict|None, additional information
80
- process: bool, whether to process extracted info
81
- force_generic_extractor: bool, force generic extractor
82
83
Returns:
84
dict: extracted information dictionary
85
"""
86
87
def process_ie_result(self, ie_result, download=True, extra_info=None):
88
"""
89
Process result from information extractor.
90
91
Parameters:
92
- ie_result: dict, result from extractor
93
- download: bool, whether to download files
94
- extra_info: dict|None, additional information
95
96
Returns:
97
dict: processed information
98
"""
99
100
def process_video_result(self, info_dict, download=True):
101
"""
102
Process information for a single video.
103
104
Parameters:
105
- info_dict: dict, video information
106
- download: bool, whether to download
107
108
Returns:
109
dict: processed video information
110
"""
111
112
@staticmethod
113
def sanitize_info(info_dict, remove_private_keys=False):
114
"""
115
Clean and sanitize information dictionary.
116
117
Parameters:
118
- info_dict: dict, information to sanitize
119
- remove_private_keys: bool, remove private keys
120
121
Returns:
122
dict: sanitized information
123
"""
124
```
125
126
### Filename and Template Processing
127
128
Methods for generating output filenames and processing output templates.
129
130
```python { .api }
131
def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
132
"""
133
Generate output filename from template and info.
134
135
Parameters:
136
- info_dict: dict, video information
137
- dir_type: str, directory type for template
138
- outtmpl: str|None, custom output template
139
- warn: bool, whether to warn on issues
140
141
Returns:
142
str: generated filename
143
"""
144
145
def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False):
146
"""
147
Process output template with information.
148
149
Parameters:
150
- outtmpl: str, output template string
151
- info_dict: dict, information for substitution
152
- sanitize: bool, whether to sanitize filename
153
154
Returns:
155
str: processed template
156
"""
157
158
@classmethod
159
def validate_outtmpl(cls, outtmpl):
160
"""
161
Validate output template syntax.
162
163
Parameters:
164
- outtmpl: str, template to validate
165
166
Returns:
167
str|None: error message if invalid, None if valid
168
"""
169
```
170
171
### Extractor Management
172
173
Methods for managing and interacting with the extractor system.
174
175
```python { .api }
176
def add_info_extractor(self, ie):
177
"""
178
Register a custom information extractor.
179
180
Parameters:
181
- ie: InfoExtractor, extractor instance to add
182
"""
183
184
def get_info_extractor(self, ie_key):
185
"""
186
Get information extractor by key.
187
188
Parameters:
189
- ie_key: str, extractor key/name
190
191
Returns:
192
InfoExtractor: extractor instance
193
"""
194
195
def add_default_info_extractors(self):
196
"""Load and register all built-in extractors."""
197
```
198
199
### Post-Processing Management
200
201
Methods for managing the post-processing pipeline.
202
203
```python { .api }
204
def add_post_processor(self, pp, when='post_process'):
205
"""
206
Add a post-processor to the pipeline.
207
208
Parameters:
209
- pp: PostProcessor, processor to add
210
- when: str, when to run ('post_process', 'after_move', etc.)
211
"""
212
213
def run_pp(self, pp, infodict):
214
"""
215
Run a single post-processor.
216
217
Parameters:
218
- pp: PostProcessor, processor to run
219
- infodict: dict, information dictionary
220
221
Returns:
222
tuple: (updated_info_dict, list_of_files_to_delete)
223
"""
224
225
def run_all_pps(self, key, info, *, additional_pps=None):
226
"""
227
Run all applicable post-processors.
228
229
Parameters:
230
- key: str, processing phase key
231
- info: dict, information dictionary
232
- additional_pps: list|None, additional processors
233
234
Returns:
235
dict: updated information dictionary
236
"""
237
```
238
239
### Progress and Event Hooks
240
241
Methods for setting up callbacks and monitoring download progress.
242
243
```python { .api }
244
def add_progress_hook(self, ph):
245
"""
246
Add download progress callback.
247
248
Parameters:
249
- ph: ProgressHook, callback function
250
"""
251
252
def add_post_hook(self, ph):
253
"""
254
Add post-download callback.
255
256
Parameters:
257
- ph: PostProcessorHook, callback function
258
"""
259
260
def add_postprocessor_hook(self, ph):
261
"""
262
Add post-processor callback.
263
264
Parameters:
265
- ph: PostProcessorHook, callback function
266
"""
267
```
268
269
### Output and Logging
270
271
Methods for controlling output and logging behavior.
272
273
```python { .api }
274
def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
275
"""
276
Print message to terminal/screen.
277
278
Parameters:
279
- message: str, message to print
280
- skip_eol: bool, skip end of line
281
- quiet: bool|None, override quiet setting
282
- only_once: bool, show message only once
283
"""
284
285
def to_stdout(self, message, skip_eol=False, quiet=None):
286
"""
287
Print message to stdout.
288
289
Parameters:
290
- message: str, message to print
291
- skip_eol: bool, skip end of line
292
- quiet: bool|None, override quiet setting
293
"""
294
295
def to_stderr(self, message, skip_eol=False, quiet=None):
296
"""
297
Print message to stderr.
298
299
Parameters:
300
- message: str, message to print
301
- skip_eol: bool, skip end of line
302
- quiet: bool|None, override quiet setting
303
"""
304
305
def write_debug(self, message, only_once=False):
306
"""
307
Write debug information.
308
309
Parameters:
310
- message: str, debug message
311
- only_once: bool, write only once per message
312
"""
313
314
def report_warning(self, message, only_once=False):
315
"""
316
Report warning message.
317
318
Parameters:
319
- message: str, warning message
320
- only_once: bool, show warning only once
321
"""
322
323
def report_error(self, message, *args, **kwargs):
324
"""
325
Report error message.
326
327
Parameters:
328
- message: str, error message
329
- *args: additional positional arguments
330
- **kwargs: additional keyword arguments
331
"""
332
```
333
334
### Network and Utilities
335
336
Methods for network operations and accessing utility functionality.
337
338
```python { .api }
339
def urlopen(self, req):
340
"""
341
Make HTTP request using configured settings.
342
343
Parameters:
344
- req: Request, request object
345
346
Returns:
347
response object
348
"""
349
350
@property
351
def cache(self):
352
"""
353
Access to cache system.
354
355
Returns:
356
Cache: cache instance
357
"""
358
```
359
360
## Usage Examples
361
362
### Basic Download with Options
363
364
```python
365
import yt_dlp
366
367
# Configure download options
368
ydl_opts = {
369
'format': 'best[height<=720]',
370
'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
371
'writesubtitles': True,
372
'writeautomaticsub': True,
373
}
374
375
# Download with options
376
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
377
ydl.download(['https://www.youtube.com/watch?v=example'])
378
```
379
380
### Information Extraction
381
382
```python
383
import yt_dlp
384
385
# Extract information without downloading
386
ydl_opts = {'skip_download': True}
387
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
388
info = ydl.extract_info('https://www.youtube.com/watch?v=example')
389
390
print(f"Title: {info['title']}")
391
print(f"Duration: {info['duration']} seconds")
392
print(f"Uploader: {info['uploader']}")
393
print(f"Upload date: {info['upload_date']}")
394
print(f"Available formats: {len(info['formats'])}")
395
```
396
397
### Progress Monitoring
398
399
```python
400
import yt_dlp
401
402
def progress_hook(d):
403
if d['status'] == 'downloading':
404
print(f"Downloading: {d['_percent_str']} of {d['_total_bytes_str']}")
405
elif d['status'] == 'finished':
406
print(f"Downloaded: {d['filename']}")
407
408
ydl_opts = {
409
'progress_hooks': [progress_hook],
410
}
411
412
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
413
ydl.download(['https://www.youtube.com/watch?v=example'])
414
```
415
416
### Custom Filename Template
417
418
```python
419
import yt_dlp
420
421
ydl_opts = {
422
'outtmpl': {
423
'default': '%(uploader)s/%(title)s [%(id)s].%(ext)s',
424
'playlist': '%(uploader)s - %(playlist)s/%(playlist_index)02d - %(title)s.%(ext)s',
425
}
426
}
427
428
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
429
ydl.download(['https://www.youtube.com/playlist?list=example'])
430
```
431
432
## Types
433
434
```python { .api }
435
# Configuration options dictionary for YoutubeDL
436
YDLOptions = dict[str, Any]
437
438
# Information dictionary returned by extractors
439
InfoDict = dict[str, Any]
440
441
# Progress hook function signature
442
ProgressHook = Callable[[dict[str, Any]], None]
443
444
# Post-processor hook function signature
445
PostProcessorHook = Callable[[dict[str, Any]], None]
446
```