0
# Configuration Options
1
2
Comprehensive configuration system with 100+ parameters controlling download behavior, format selection, output templates, networking, post-processing options, and other aspects of yt-dlp operation. Configuration can be provided via dictionary to YoutubeDL constructor or parsed from command-line arguments.
3
4
## Capabilities
5
6
### CLI and Parsing Functions
7
8
Functions for command-line interface operation and parsing arguments into configuration dictionaries.
9
10
```python { .api }
11
def main(argv=None):
12
"""
13
Main CLI entry point for yt-dlp command-line interface.
14
15
Parses arguments, sets up YoutubeDL instance, and executes downloads
16
with proper error handling and exit codes.
17
18
Parameters:
19
- argv: list[str]|None, command-line arguments (default: sys.argv)
20
21
Returns:
22
None: exits with appropriate exit code
23
"""
24
25
def parse_options(argv=None):
26
"""
27
Main option parsing function that processes command-line arguments.
28
29
Parameters:
30
- argv: list[str]|None, command-line arguments (default: sys.argv)
31
32
Returns:
33
ParsedOptions: named tuple with (parser, options, urls, ydl_opts)
34
"""
35
36
def parseOpts(overrideArguments=None, ignore_config_files='if_override'):
37
"""
38
Parse command-line options and return configuration.
39
40
Parameters:
41
- overrideArguments: list[str]|None, arguments to use instead of sys.argv
42
- ignore_config_files: str, how to handle config files ('if_override', 'always', 'never')
43
44
Returns:
45
tuple: (parser, options, urls) where options contains parsed configuration
46
"""
47
```
48
49
### Core Configuration Categories
50
51
#### Download and Format Selection
52
53
Options controlling what content to download and in what format.
54
55
```python { .api }
56
# Format selection and quality options
57
YDLOptions = {
58
'format': str, # Format selector string (e.g., 'best', 'worst', 'mp4')
59
'format_sort': list[str], # Format sorting criteria
60
'format_sort_force': bool, # Force format sorting
61
'listformats': bool, # List available formats instead of downloading
62
'listformats_table': bool, # Use table format for format listing
63
64
# Quality and size limits
65
'min_filesize': int, # Minimum file size in bytes
66
'max_filesize': int, # Maximum file size in bytes
67
'min_views': int, # Minimum view count
68
'max_views': int, # Maximum view count
69
70
# Multiple streams
71
'allow_multiple_video_streams': bool, # Allow multiple video streams
72
'allow_multiple_audio_streams': bool, # Allow multiple audio streams
73
'allow_unplayable_formats': bool, # Allow unplayable formats
74
'ignore_no_formats_error': bool, # Ignore no formats error
75
'check_formats': str, # Check format availability
76
}
77
```
78
79
#### Output and Filesystem Options
80
81
Options controlling where and how files are saved.
82
83
```python { .api }
84
# Output templates and paths
85
YDLOptions = {
86
'outtmpl': dict[str, str], # Output filename templates by type
87
'outtmpl_na_placeholder': str, # Placeholder for unavailable fields
88
'paths': dict[str, str], # Output paths by type
89
'restrictfilenames': bool, # Restrict filenames to ASCII
90
'windowsfilenames': bool, # Use Windows-compatible filenames
91
'trim_file_name': int, # Maximum filename length
92
93
# File handling
94
'overwrites': bool, # Overwrite existing files
95
'nopart': bool, # Don't use .part files
96
'updatetime': bool, # Update file modification times
97
'continuedl': bool, # Continue partial downloads
98
'noresizebuffer': bool, # Don't resize download buffer
99
100
# Directory and file organization
101
'allow_playlist_files': bool, # Allow playlist info files
102
'clean_infojson': bool, # Clean info JSON files
103
}
104
```
105
106
#### Network and Connection Options
107
108
Options controlling network behavior, requests, and connectivity.
109
110
```python { .api }
111
# Network configuration
112
YDLOptions = {
113
'proxy': str, # HTTP/HTTPS proxy URL
114
'socket_timeout': float, # Socket timeout in seconds
115
'source_address': str, # Source IP address to bind to
116
'cn_verification_proxy': str, # Proxy for CN verification
117
'geo_verification_proxy': str, # Proxy for geo verification
118
'geo_bypass': bool, # Attempt geo bypass
119
'geo_bypass_country': str, # Country code for geo bypass
120
'geo_bypass_ip_block': str, # IP block for geo bypass
121
122
# Request headers and user agent
123
'http_headers': dict[str, str], # Custom HTTP headers
124
'user_agent': str, # Custom user agent string
125
'referer': str, # Custom referer header
126
127
# Connection behavior
128
'nocheckcertificate': bool, # Skip SSL certificate verification
129
'prefer_insecure': bool, # Prefer insecure connections
130
'enable_file_urls': bool, # Enable file:// URLs
131
'legacyserverconnect': bool, # Use legacy server connect
132
133
# Rate limiting and retries
134
'ratelimit': int, # Download rate limit in bytes/sec
135
'throttledratelimit': int, # Throttled rate limit
136
'retries': int, # Number of download retries
137
'file_access_retries': int, # File access retries
138
'fragment_retries': int, # Fragment download retries
139
'extractor_retries': int, # Extractor retries
140
'retry_sleep_functions': dict, # Retry sleep functions
141
142
# Request timing
143
'sleep_interval': float, # Sleep between requests
144
'max_sleep_interval': float, # Maximum sleep interval
145
'sleep_interval_requests': float, # Sleep between requests
146
'sleep_interval_subtitles': float, # Sleep between subtitle requests
147
}
148
```
149
150
#### Authentication and Cookies
151
152
Options for handling authentication, login credentials, and cookies.
153
154
```python { .api }
155
# Authentication options
156
YDLOptions = {
157
'username': str, # Account username
158
'password': str, # Account password
159
'twofactor': str, # Two-factor authentication code
160
'videopassword': str, # Video-specific password
161
'usenetrc': bool, # Use .netrc file for credentials
162
'netrc_location': str, # Custom .netrc file location
163
'netrc_cmd': str, # Command to get credentials
164
165
# TV provider authentication
166
'ap_mso': str, # TV provider MSO
167
'ap_username': str, # TV provider username
168
'ap_password': str, # TV provider password
169
170
# Client certificates
171
'client_certificate': str, # Client certificate file
172
'client_certificate_key': str, # Client certificate key file
173
'client_certificate_password': str, # Client certificate password
174
175
# Cookie handling
176
'cookiefile': str, # Cookie file path
177
'cookiesfrombrowser': tuple, # Extract cookies from browser
178
}
179
```
180
181
#### Playlist and Batch Processing
182
183
Options for handling playlists, channels, and batch operations.
184
185
```python { .api }
186
# Playlist options
187
YDLOptions = {
188
'playliststart': int, # Playlist start index
189
'playlistend': int, # Playlist end index
190
'playlistreverse': bool, # Reverse playlist order
191
'playlistrandom': bool, # Randomize playlist order
192
'lazy_playlist': bool, # Lazy playlist loading
193
'noplaylist': bool, # Download single video instead of playlist
194
'extract_flat': str, # Extract playlist info only
195
'playlist_items': str, # Specific playlist items to download
196
197
# Batch processing
198
'max_downloads': int, # Maximum number of downloads
199
'break_on_existing': bool, # Stop on existing files
200
'break_on_reject': bool, # Stop on rejected videos
201
'break_per_url': bool, # Break processing per URL
202
'skip_playlist_after_errors': int, # Skip playlist after N errors
203
204
# Archive and filtering
205
'download_archive': str, # Download archive file path
206
'force_write_download_archive': bool, # Force writing archive
207
'match_filter': callable, # Match filter function
208
'daterange': object, # Date range filter
209
}
210
```
211
212
#### Output Control and Information
213
214
Options controlling what information is displayed and how.
215
216
```python { .api }
217
# Output and logging options
218
YDLOptions = {
219
'quiet': bool, # Suppress output messages
220
'no_warnings': bool, # Suppress warning messages
221
'verbose': bool, # Enable verbose output
222
'noprogress': bool, # Disable progress reporting
223
'progress_with_newline': bool, # Progress on new lines
224
'progress_template': dict[str, str], # Progress message templates
225
'progress_delta': float, # Progress update interval
226
'consoletitle': bool, # Set console title
227
'color': dict[str, str], # Color configuration
228
229
# Information extraction
230
'forceurl': bool, # Force URL extraction
231
'forcetitle': bool, # Force title extraction
232
'forceid': bool, # Force ID extraction
233
'forcethumbnail': bool, # Force thumbnail extraction
234
'forcedescription': bool, # Force description extraction
235
'forceduration': bool, # Force duration extraction
236
'forcefilename': bool, # Force filename extraction
237
'forceformat': bool, # Force format extraction
238
'forceprint': dict[str, list], # Force print specific fields
239
'print_to_file': dict[str, list], # Print to file
240
'forcejson': bool, # Force JSON output
241
'dump_single_json': bool, # Dump single JSON
242
243
# File output options
244
'simulate': bool, # Simulate download
245
'skip_download': bool, # Skip actual download
246
'logtostderr': bool, # Log to stderr
247
'writedescription': bool, # Write description file
248
'writeinfojson': bool, # Write info JSON file
249
'writeannotations': bool, # Write annotations file
250
'writelink': bool, # Write link file
251
'writeurllink': bool, # Write URL link file
252
'writewebloclink': bool, # Write webloc link file
253
'writedesktoplink': bool, # Write desktop link file
254
}
255
```
256
257
#### Subtitle and Caption Options
258
259
Options for handling subtitles, captions, and text content.
260
261
```python { .api }
262
# Subtitle options
263
YDLOptions = {
264
'writesubtitles': bool, # Write subtitle files
265
'writeautomaticsub': bool, # Write automatic subtitles
266
'allsubtitles': bool, # Download all available subtitles
267
'listsubtitles': bool, # List available subtitles
268
'subtitlesformat': str, # Subtitle format preference
269
'subtitleslangs': list[str], # Subtitle language codes
270
271
# Caption processing
272
'getcomments': bool, # Extract comments
273
'embedsubtitles': bool, # Embed subtitles in video
274
'convertsubtitles': str, # Convert subtitle format
275
}
276
```
277
278
#### Thumbnail and Image Options
279
280
Options for handling thumbnail images and visual content.
281
282
```python { .api }
283
# Thumbnail options
284
YDLOptions = {
285
'writethumbnail': bool, # Write thumbnail file
286
'write_all_thumbnails': bool, # Write all available thumbnails
287
'list_thumbnails': bool, # List available thumbnails
288
'embedthumbnail': bool, # Embed thumbnail in media
289
'convertthumbnails': str, # Convert thumbnail format
290
}
291
```
292
293
#### Advanced Processing Options
294
295
Advanced options for specialized processing and customization.
296
297
```python { .api }
298
# Advanced options
299
YDLOptions = {
300
# Extractor options
301
'allowed_extractors': list[str], # Allowed extractor list
302
'force_generic_extractor': bool, # Force generic extractor
303
'default_search': str, # Default search prefix
304
'age_limit': int, # Age limit for content
305
'extractor_args': dict, # Extractor-specific arguments
306
307
# Processing options
308
'external_downloader': dict, # External downloader configuration
309
'external_downloader_args': dict, # External downloader arguments
310
'postprocessors': list[dict], # Post-processor configuration
311
'postprocessor_args': dict, # Post-processor arguments
312
'fixup': str, # Video fixup mode
313
'merge_output_format': str, # Merge output format
314
'final_ext': str, # Final file extension
315
316
# Experimental options
317
'dynamic_mpd': bool, # Dynamic MPD support
318
'hls_prefer_native': bool, # Prefer native HLS
319
'hls_use_mpegts': bool, # Use MPEGTS for HLS
320
'hls_split_discontinuity': bool, # Split on HLS discontinuity
321
'include_ads': bool, # Include advertisements
322
'mark_watched': bool, # Mark videos as watched
323
324
# Hook functions
325
'progress_hooks': list[callable], # Progress hook functions
326
'postprocessor_hooks': list[callable], # Post-processor hooks
327
328
# Internal options
329
'test': bool, # Test mode
330
'keepvideo': bool, # Keep video after extraction
331
'encoding': str, # Text encoding
332
}
333
```
334
335
## Usage Examples
336
337
### Basic Download Configuration
338
339
```python
340
import yt_dlp
341
342
# Simple configuration
343
ydl_opts = {
344
'format': 'best[height<=720]',
345
'outtmpl': '%(title)s.%(ext)s',
346
'writesubtitles': True,
347
}
348
349
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
350
ydl.download(['https://www.youtube.com/watch?v=example'])
351
```
352
353
### Advanced Configuration
354
355
```python
356
import yt_dlp
357
358
# Comprehensive configuration
359
ydl_opts = {
360
# Format selection
361
'format': 'best[height<=1080][ext=mp4]/best[height<=1080]/best',
362
'format_sort': ['res:1080', 'ext:mp4', 'vcodec:h264'],
363
364
# Output configuration
365
'outtmpl': {
366
'default': '%(uploader)s/%(title)s [%(id)s].%(ext)s',
367
'playlist': '%(uploader)s - %(playlist)s/%(playlist_index)02d - %(title)s.%(ext)s',
368
},
369
'restrictfilenames': True,
370
'trim_file_name': 200,
371
372
# Network settings
373
'socket_timeout': 30,
374
'retries': 3,
375
'sleep_interval': 1,
376
377
# Subtitles and metadata
378
'writesubtitles': True,
379
'writeautomaticsub': True,
380
'subtitleslangs': ['en', 'es'],
381
'writeinfojson': True,
382
'writethumbnail': True,
383
384
# Post-processing
385
'postprocessors': [
386
{
387
'key': 'FFmpegSubtitlesConvertor',
388
'format': 'srt',
389
},
390
{
391
'key': 'FFmpegMetadata',
392
'add_metadata': True,
393
},
394
{
395
'key': 'EmbedThumbnail',
396
},
397
],
398
399
# Progress monitoring
400
'progress_hooks': [lambda d: print(f"Status: {d['status']}")],
401
}
402
403
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
404
ydl.download(['https://www.youtube.com/watch?v=example'])
405
```
406
407
### Playlist Configuration
408
409
```python
410
import yt_dlp
411
412
# Playlist-specific configuration
413
ydl_opts = {
414
'format': 'best[height<=720]',
415
'playliststart': 1,
416
'playlistend': 10,
417
'outtmpl': '%(playlist_title)s/%(playlist_index)02d - %(title)s.%(ext)s',
418
'writeinfojson': True,
419
'extract_flat': False,
420
'skip_playlist_after_errors': 3,
421
}
422
423
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
424
ydl.download(['https://www.youtube.com/playlist?list=example'])
425
```
426
427
### Audio Extraction Configuration
428
429
```python
430
import yt_dlp
431
432
# Audio-only configuration
433
ydl_opts = {
434
'format': 'bestaudio/best',
435
'outtmpl': '%(artist)s - %(title)s.%(ext)s',
436
'postprocessors': [{
437
'key': 'FFmpegExtractAudio',
438
'preferredcodec': 'mp3',
439
'preferredquality': '192',
440
}],
441
'extractaudio': True,
442
'audioformat': 'mp3',
443
'embed_infojson': True,
444
}
445
446
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
447
ydl.download(['https://www.youtube.com/watch?v=example'])
448
```
449
450
### Command-Line Parsing
451
452
```python
453
import yt_dlp
454
455
# Parse command-line options
456
args = ['--format', 'best[height<=720]', '--write-subs', 'https://www.youtube.com/watch?v=example']
457
parsed = yt_dlp.parse_options(args)
458
459
print(f"URLs: {parsed.urls}")
460
print(f"Format: {parsed.ydl_opts.get('format')}")
461
print(f"Write subs: {parsed.ydl_opts.get('writesubtitles')}")
462
463
# Use parsed options
464
with yt_dlp.YoutubeDL(parsed.ydl_opts) as ydl:
465
ydl.download(parsed.urls)
466
```
467
468
### Network Configuration
469
470
```python
471
import yt_dlp
472
473
# Network-specific configuration
474
ydl_opts = {
475
'proxy': 'http://proxy.example.com:8080',
476
'socket_timeout': 60,
477
'source_address': '192.168.1.100',
478
'http_headers': {
479
'User-Agent': 'Mozilla/5.0 (Custom User Agent)',
480
'Accept-Language': 'en-US,en;q=0.9',
481
},
482
'retries': 5,
483
'sleep_interval': 2,
484
'cookiefile': '/path/to/cookies.txt',
485
}
486
487
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
488
ydl.download(['https://www.youtube.com/watch?v=example'])
489
```
490
491
## Types
492
493
```python { .api }
494
# Main configuration options type
495
YDLOptions = dict[str, Any]
496
497
# Parsed options result
498
class ParsedOptions:
499
parser: argparse.ArgumentParser
500
options: argparse.Namespace
501
urls: list[str]
502
ydl_opts: YDLOptions
503
504
# Progress hook function signature
505
ProgressHook = Callable[[dict[str, Any]], None]
506
507
# Post-processor configuration
508
PostProcessorDict = dict[str, Any]
509
510
# Format selector string patterns
511
FormatSelector = str # e.g., 'best', 'worst', 'mp4', 'best[height<=720]'
512
513
# Output template string with field substitution
514
OutputTemplate = str # e.g., '%(title)s.%(ext)s'
515
```