]> jfr.im git - yt-dlp.git/blob - youtube_dlc/options.py
Portable Configuration file (closes #19)
[yt-dlp.git] / youtube_dlc / options.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import optparse
5 import re
6 import sys
7
8 from .downloader.external import list_external_downloaders
9 from .compat import (
10 compat_expanduser,
11 compat_get_terminal_size,
12 compat_getenv,
13 compat_kwargs,
14 compat_shlex_split,
15 )
16 from .utils import (
17 preferredencoding,
18 write_string,
19 )
20 from .version import __version__
21
22
23 def _hide_login_info(opts):
24 PRIVATE_OPTS = set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
25 eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
26
27 def _scrub_eq(o):
28 m = eqre.match(o)
29 if m:
30 return m.group('key') + '=PRIVATE'
31 else:
32 return o
33
34 opts = list(map(_scrub_eq, opts))
35 for idx, opt in enumerate(opts):
36 if opt in PRIVATE_OPTS and idx + 1 < len(opts):
37 opts[idx + 1] = 'PRIVATE'
38 return opts
39
40
41 def parseOpts(overrideArguments=None):
42 def _readOptions(filename_bytes, default=[]):
43 try:
44 optionf = open(filename_bytes)
45 except IOError:
46 return default # silently skip if file is not present
47 try:
48 # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
49 contents = optionf.read()
50 if sys.version_info < (3,):
51 contents = contents.decode(preferredencoding())
52 res = compat_shlex_split(contents, comments=True)
53 finally:
54 optionf.close()
55 return res
56
57 def _readUserConf(package_name, default=[]):
58 # .config
59 xdg_config_home = compat_getenv('XDG_CONFIG_HOME') or compat_expanduser('~/.config')
60 userConfFile = os.path.join(xdg_config_home, package_name, 'config')
61 if not os.path.isfile(userConfFile):
62 userConfFile = os.path.join(xdg_config_home, '%s.conf' % package_name)
63 userConf = _readOptions(userConfFile, default=None)
64 if userConf is not None:
65 return userConf
66
67 # appdata
68 appdata_dir = compat_getenv('appdata')
69 if appdata_dir:
70 userConfFile = os.path.join(appdata_dir, package_name, 'config')
71 userConf = _readOptions(userConfFile, default=None)
72 if userConf is None:
73 userConf = _readOptions('%s.txt' % userConfFile, default=None)
74 if userConf is not None:
75 return userConf
76
77 # home
78 userConfFile = os.path.join(compat_expanduser('~'), '%s.conf' % package_name)
79 userConf = _readOptions(userConfFile, default=None)
80 if userConf is None:
81 userConf = _readOptions('%s.txt' % userConfFile, default=None)
82 if userConf is not None:
83 return userConf
84
85 return default
86
87 def _format_option_string(option):
88 ''' ('-o', '--option') -> -o, --format METAVAR'''
89
90 opts = []
91
92 if option._short_opts:
93 opts.append(option._short_opts[0])
94 if option._long_opts:
95 opts.append(option._long_opts[0])
96 if len(opts) > 1:
97 opts.insert(1, ', ')
98
99 if option.takes_value():
100 opts.append(' %s' % option.metavar)
101
102 return ''.join(opts)
103
104 def _comma_separated_values_options_callback(option, opt_str, value, parser):
105 setattr(parser.values, option.dest, value.split(','))
106
107 # No need to wrap help messages if we're on a wide console
108 columns = compat_get_terminal_size().columns
109 max_width = columns if columns else 80
110 max_help_position = 80
111
112 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
113 fmt.format_option_strings = _format_option_string
114
115 kw = {
116 'version': __version__,
117 'formatter': fmt,
118 'usage': '%prog [OPTIONS] URL [URL...]',
119 'conflict_handler': 'resolve',
120 }
121
122 parser = optparse.OptionParser(**compat_kwargs(kw))
123
124 general = optparse.OptionGroup(parser, 'General Options')
125 general.add_option(
126 '-h', '--help',
127 action='help',
128 help='Print this help text and exit')
129 general.add_option(
130 '--version',
131 action='version',
132 help='Print program version and exit')
133 general.add_option(
134 '-U', '--update',
135 action='store_true', dest='update_self',
136 help='[BROKEN] Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
137 general.add_option(
138 '-i', '--ignore-errors', '--no-abort-on-error',
139 action='store_true', dest='ignoreerrors', default=True,
140 help='Continue on download errors, for example to skip unavailable videos in a playlist (default)')
141 general.add_option(
142 '--abort-on-error', '--no-ignore-errors',
143 action='store_false', dest='ignoreerrors',
144 help='Abort downloading of further videos if an error occurs')
145 general.add_option(
146 '--dump-user-agent',
147 action='store_true', dest='dump_user_agent', default=False,
148 help='Display the current browser identification')
149 general.add_option(
150 '--list-extractors',
151 action='store_true', dest='list_extractors', default=False,
152 help='List all supported extractors')
153 general.add_option(
154 '--extractor-descriptions',
155 action='store_true', dest='list_extractor_descriptions', default=False,
156 help='Output descriptions of all supported extractors')
157 general.add_option(
158 '--force-generic-extractor',
159 action='store_true', dest='force_generic_extractor', default=False,
160 help='Force extraction to use the generic extractor')
161 general.add_option(
162 '--default-search',
163 dest='default_search', metavar='PREFIX',
164 help='Use this prefix for unqualified URLs. For example "gvsearch2:" downloads two videos from google videos for youtube-dl "large apple". Use the value "auto" to let youtube-dl guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching.')
165 general.add_option(
166 '--ignore-config', '--no-config',
167 action='store_true',
168 help=(
169 'Do not read configuration files. '
170 'When given in the global configuration file /etc/youtube-dl.conf: '
171 'Do not read the user configuration in ~/.config/youtube-dl/config '
172 '(%APPDATA%/youtube-dl/config.txt on Windows)'))
173 general.add_option(
174 '--config-location',
175 dest='config_location', metavar='PATH',
176 help='Location of the configuration file; either the path to the config or its containing directory.')
177 general.add_option(
178 '--flat-playlist',
179 action='store_const', dest='extract_flat', const='in_playlist', default=False,
180 help='Do not extract the videos of a playlist, only list them.')
181 general.add_option(
182 '--flat-videos',
183 action='store_true', dest='extract_flat',
184 help='Do not resolve the video urls')
185 general.add_option(
186 '--no-flat-playlist',
187 action='store_false', dest='extract_flat',
188 help='Extract the videos of a playlist')
189 general.add_option(
190 '--mark-watched',
191 action='store_true', dest='mark_watched', default=False,
192 help='Mark videos watched (YouTube only)')
193 general.add_option(
194 '--no-mark-watched',
195 action='store_false', dest='mark_watched', default=False,
196 help='Do not mark videos watched')
197 general.add_option(
198 '--no-color', '--no-colors',
199 action='store_true', dest='no_color',
200 default=False,
201 help='Do not emit color codes in output')
202
203 network = optparse.OptionGroup(parser, 'Network Options')
204 network.add_option(
205 '--proxy', dest='proxy',
206 default=None, metavar='URL',
207 help=(
208 'Use the specified HTTP/HTTPS/SOCKS proxy. To enable '
209 'SOCKS proxy, specify a proper scheme. For example '
210 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
211 'for direct connection'))
212 network.add_option(
213 '--socket-timeout',
214 dest='socket_timeout', type=float, default=None, metavar='SECONDS',
215 help='Time to wait before giving up, in seconds')
216 network.add_option(
217 '--source-address',
218 metavar='IP', dest='source_address', default=None,
219 help='Client-side IP address to bind to',
220 )
221 network.add_option(
222 '-4', '--force-ipv4',
223 action='store_const', const='0.0.0.0', dest='source_address',
224 help='Make all connections via IPv4',
225 )
226 network.add_option(
227 '-6', '--force-ipv6',
228 action='store_const', const='::', dest='source_address',
229 help='Make all connections via IPv6',
230 )
231
232 geo = optparse.OptionGroup(parser, 'Geo Restriction')
233 geo.add_option(
234 '--geo-verification-proxy',
235 dest='geo_verification_proxy', default=None, metavar='URL',
236 help=(
237 'Use this proxy to verify the IP address for some geo-restricted sites. '
238 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.'))
239 geo.add_option(
240 '--cn-verification-proxy',
241 dest='cn_verification_proxy', default=None, metavar='URL',
242 help=optparse.SUPPRESS_HELP)
243 geo.add_option(
244 '--geo-bypass',
245 action='store_true', dest='geo_bypass', default=True,
246 help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')
247 geo.add_option(
248 '--no-geo-bypass',
249 action='store_false', dest='geo_bypass', default=True,
250 help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
251 geo.add_option(
252 '--geo-bypass-country', metavar='CODE',
253 dest='geo_bypass_country', default=None,
254 help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
255 geo.add_option(
256 '--geo-bypass-ip-block', metavar='IP_BLOCK',
257 dest='geo_bypass_ip_block', default=None,
258 help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
259
260 selection = optparse.OptionGroup(parser, 'Video Selection')
261 selection.add_option(
262 '--playlist-start',
263 dest='playliststart', metavar='NUMBER', default=1, type=int,
264 help='Playlist video to start at (default is %default)')
265 selection.add_option(
266 '--playlist-end',
267 dest='playlistend', metavar='NUMBER', default=None, type=int,
268 help='Playlist video to end at (default is last)')
269 selection.add_option(
270 '--playlist-items',
271 dest='playlist_items', metavar='ITEM_SPEC', default=None,
272 help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.')
273 selection.add_option(
274 '--match-title',
275 dest='matchtitle', metavar='REGEX',
276 help='Download only matching titles (regex or caseless sub-string)')
277 selection.add_option(
278 '--reject-title',
279 dest='rejecttitle', metavar='REGEX',
280 help='Skip download for matching titles (regex or caseless sub-string)')
281 selection.add_option(
282 '--max-downloads',
283 dest='max_downloads', metavar='NUMBER', type=int, default=None,
284 help='Abort after downloading NUMBER files')
285 selection.add_option(
286 '--min-filesize',
287 metavar='SIZE', dest='min_filesize', default=None,
288 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
289 selection.add_option(
290 '--max-filesize',
291 metavar='SIZE', dest='max_filesize', default=None,
292 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
293 selection.add_option(
294 '--date',
295 metavar='DATE', dest='date', default=None,
296 help=(
297 'Download only videos uploaded in this date.'
298 'The date can be "YYYYMMDD" or in the format'
299 '"(now|today)[+-][0-9](day|week|month|year)(s)?"'))
300 selection.add_option(
301 '--datebefore',
302 metavar='DATE', dest='datebefore', default=None,
303 help=(
304 'Download only videos uploaded on or before this date. '
305 'The date formats accepted is the same as --date'))
306 selection.add_option(
307 '--dateafter',
308 metavar='DATE', dest='dateafter', default=None,
309 help=(
310 'Download only videos uploaded on or after this date. '
311 'The date formats accepted is the same as --date'))
312 selection.add_option(
313 '--min-views',
314 metavar='COUNT', dest='min_views', default=None, type=int,
315 help='Do not download any videos with less than COUNT views')
316 selection.add_option(
317 '--max-views',
318 metavar='COUNT', dest='max_views', default=None, type=int,
319 help='Do not download any videos with more than COUNT views')
320 selection.add_option(
321 '--match-filter',
322 metavar='FILTER', dest='match_filter', default=None,
323 help=(
324 'Generic video filter. '
325 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to '
326 'match if the key is present, '
327 '!key to check if the key is not present, '
328 'key > NUMBER (like "comment_count > 12", also works with '
329 '>=, <, <=, !=, =) to compare against a number, '
330 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
331 'to match against a string literal '
332 'and & to require multiple matches. '
333 'Values which are not known are excluded unless you '
334 'put a question mark (?) after the operator. '
335 'For example, to only match videos that have been liked more than '
336 '100 times and disliked less than 50 times (or the dislike '
337 'functionality is not available at the given service), but who '
338 'also have a description, use --match-filter '
339 '"like_count > 100 & dislike_count <? 50 & description" .'))
340 selection.add_option(
341 '--no-match-filter',
342 metavar='FILTER', dest='match_filter', action='store_const', const=None,
343 help='Do not use generic video filter (default)')
344 selection.add_option(
345 '--no-playlist',
346 action='store_true', dest='noplaylist', default=False,
347 help='Download only the video, if the URL refers to a video and a playlist.')
348 selection.add_option(
349 '--yes-playlist',
350 action='store_false', dest='noplaylist', default=False,
351 help='Download the playlist, if the URL refers to a video and a playlist.')
352 selection.add_option(
353 '--age-limit',
354 metavar='YEARS', dest='age_limit', default=None, type=int,
355 help='Download only videos suitable for the given age')
356 selection.add_option(
357 '--download-archive', metavar='FILE',
358 dest='download_archive',
359 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
360 selection.add_option(
361 '--break-on-existing',
362 action='store_true', dest='break_on_existing', default=False,
363 help="Stop the download process when encountering a file that's in the archive.")
364 selection.add_option(
365 '--break-on-reject',
366 action='store_true', dest='break_on_reject', default=False,
367 help="Stop the download process when encountering a file that has been filtered out.")
368 selection.add_option(
369 '--no-download-archive',
370 dest='download_archive', action="store_const", const=None,
371 help='Do not use archive file (default)')
372 selection.add_option(
373 '--include-ads',
374 dest='include_ads', action='store_true',
375 help='Download advertisements as well (experimental)')
376 selection.add_option(
377 '--no-include-ads',
378 dest='include_ads', action='store_false',
379 help='Do not download advertisements (default)')
380
381 authentication = optparse.OptionGroup(parser, 'Authentication Options')
382 authentication.add_option(
383 '-u', '--username',
384 dest='username', metavar='USERNAME',
385 help='Login with this account ID')
386 authentication.add_option(
387 '-p', '--password',
388 dest='password', metavar='PASSWORD',
389 help='Account password. If this option is left out, youtube-dlc will ask interactively.')
390 authentication.add_option(
391 '-2', '--twofactor',
392 dest='twofactor', metavar='TWOFACTOR',
393 help='Two-factor authentication code')
394 authentication.add_option(
395 '-n', '--netrc',
396 action='store_true', dest='usenetrc', default=False,
397 help='Use .netrc authentication data')
398 authentication.add_option(
399 '--video-password',
400 dest='videopassword', metavar='PASSWORD',
401 help='Video password (vimeo, youku)')
402
403 adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
404 adobe_pass.add_option(
405 '--ap-mso',
406 dest='ap_mso', metavar='MSO',
407 help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
408 adobe_pass.add_option(
409 '--ap-username',
410 dest='ap_username', metavar='USERNAME',
411 help='Multiple-system operator account login')
412 adobe_pass.add_option(
413 '--ap-password',
414 dest='ap_password', metavar='PASSWORD',
415 help='Multiple-system operator account password. If this option is left out, youtube-dlc will ask interactively.')
416 adobe_pass.add_option(
417 '--ap-list-mso',
418 action='store_true', dest='ap_list_mso', default=False,
419 help='List all supported multiple-system operators')
420
421 video_format = optparse.OptionGroup(parser, 'Video Format Options')
422 video_format.add_option(
423 '-f', '--format',
424 action='store', dest='format', metavar='FORMAT', default=None,
425 help='Video format code, see "FORMAT SELECTION" for more details')
426 video_format.add_option(
427 '-S', '--format-sort', metavar='SORTORDER',
428 dest='format_sort', default=[],
429 action='callback', callback=_comma_separated_values_options_callback, type='str',
430 help='Sort the formats by the fields given, see "Sorting Formats" for more details')
431 video_format.add_option(
432 '--format-sort-force', '--S-force',
433 action='store_true', dest='format_sort_force', metavar='FORMAT', default=False,
434 help=(
435 'Force user specified sort order to have precedence over all fields, '
436 'see "Sorting Formats" for more details'))
437 video_format.add_option(
438 '--no-format-sort-force',
439 action='store_false', dest='format_sort_force', metavar='FORMAT', default=False,
440 help=(
441 'Some fields have precedence over the user specified sort order (default), '
442 'see "Sorting Formats" for more details'))
443 video_format.add_option(
444 '--video-multistreams',
445 action='store_true', dest='allow_multiple_video_streams', default=False,
446 help='Allow multiple video streams to be merged into a single file')
447 video_format.add_option(
448 '--no-video-multistreams',
449 action='store_false', dest='allow_multiple_video_streams',
450 help='Only one video stream is downloaded for each output file (default)')
451 video_format.add_option(
452 '--audio-multistreams',
453 action='store_true', dest='allow_multiple_audio_streams', default=False,
454 help='Allow multiple audio streams to be merged into a single file')
455 video_format.add_option(
456 '--no-audio-multistreams',
457 action='store_false', dest='allow_multiple_audio_streams',
458 help='Only one audio stream is downloaded for each output file (default)')
459 video_format.add_option(
460 '--all-formats',
461 action='store_const', dest='format', const='all',
462 help='Download all available video formats')
463 video_format.add_option(
464 '--prefer-free-formats',
465 action='store_true', dest='prefer_free_formats', default=False,
466 help='Prefer free video formats over non-free formats of same quality')
467 video_format.add_option(
468 '-F', '--list-formats',
469 action='store_true', dest='listformats',
470 help='List all available formats of requested videos')
471 video_format.add_option(
472 '--list-formats-as-table',
473 action='store_true', dest='listformats_table', default=True,
474 help='Present the output of -F in a more tabular form (default)')
475 video_format.add_option(
476 '--list-formats-old', '--no-list-formats-as-table',
477 action='store_false', dest='listformats_table',
478 help='Present the output of -F in the old form')
479 video_format.add_option(
480 '--youtube-include-dash-manifest', '--no-youtube-skip-dash-manifest',
481 action='store_true', dest='youtube_include_dash_manifest', default=True,
482 help='Download the DASH manifests and related data on YouTube videos (default)')
483 video_format.add_option(
484 '--youtube-skip-dash-manifest', '--no-youtube-include-dash-manifest',
485 action='store_false', dest='youtube_include_dash_manifest',
486 help='Do not download the DASH manifests and related data on YouTube videos')
487 video_format.add_option(
488 '--youtube-include-hls-manifest', '--no-youtube-skip-hls-manifest',
489 action='store_true', dest='youtube_include_hls_manifest', default=True,
490 help='Download the HLS manifests and related data on YouTube videos (default)')
491 video_format.add_option(
492 '--youtube-skip-hls-manifest', '--no-youtube-include-hls-manifest',
493 action='store_false', dest='youtube_include_hls_manifest',
494 help='Do not download the HLS manifests and related data on YouTube videos')
495 video_format.add_option(
496 '--merge-output-format',
497 action='store', dest='merge_output_format', metavar='FORMAT', default=None,
498 help=(
499 'If a merge is required (e.g. bestvideo+bestaudio), '
500 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
501 'Ignored if no merge is required'))
502
503 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
504 subtitles.add_option(
505 '--write-subs', '--write-srt',
506 action='store_true', dest='writesubtitles', default=False,
507 help='Write subtitle file')
508 subtitles.add_option(
509 '--no-write-subs', '--no-write-srt',
510 action='store_false', dest='writesubtitles',
511 help='Do not write subtitle file (default)')
512 subtitles.add_option(
513 '--write-auto-subs', '--write-automatic-subs',
514 action='store_true', dest='writeautomaticsub', default=False,
515 help='Write automatically generated subtitle file (YouTube only)')
516 subtitles.add_option(
517 '--no-write-auto-subs', '--no-write-automatic-subs',
518 action='store_false', dest='writeautomaticsub', default=False,
519 help='Do not write automatically generated subtitle file (default)')
520 subtitles.add_option(
521 '--all-subs',
522 action='store_true', dest='allsubtitles', default=False,
523 help='Download all the available subtitles of the video')
524 subtitles.add_option(
525 '--list-subs',
526 action='store_true', dest='listsubtitles', default=False,
527 help='List all available subtitles for the video')
528 subtitles.add_option(
529 '--sub-format',
530 action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
531 help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
532 subtitles.add_option(
533 '--sub-lang', '--sub-langs', '--srt-lang',
534 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
535 default=[], callback=_comma_separated_values_options_callback,
536 help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
537
538 downloader = optparse.OptionGroup(parser, 'Download Options')
539 downloader.add_option(
540 '-r', '--limit-rate', '--rate-limit',
541 dest='ratelimit', metavar='RATE',
542 help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
543 downloader.add_option(
544 '-R', '--retries',
545 dest='retries', metavar='RETRIES', default=10,
546 help='Number of retries (default is %default), or "infinite".')
547 downloader.add_option(
548 '--fragment-retries',
549 dest='fragment_retries', metavar='RETRIES', default=10,
550 help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
551 downloader.add_option(
552 '--skip-unavailable-fragments', '--no-abort-on-unavailable-fragment',
553 action='store_true', dest='skip_unavailable_fragments', default=True,
554 help='Skip unavailable fragments for DASH, hlsnative and ISM (default)')
555 downloader.add_option(
556 '--abort-on-unavailable-fragment', '--no-skip-unavailable-fragments',
557 action='store_false', dest='skip_unavailable_fragments',
558 help='Abort downloading when some fragment is unavailable')
559 downloader.add_option(
560 '--keep-fragments',
561 action='store_true', dest='keep_fragments', default=False,
562 help='Keep downloaded fragments on disk after downloading is finished')
563 downloader.add_option(
564 '--no-keep-fragments',
565 action='store_false', dest='keep_fragments',
566 help='Delete downloaded fragments after downloading is finished (default)')
567 downloader.add_option(
568 '--buffer-size',
569 dest='buffersize', metavar='SIZE', default='1024',
570 help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
571 downloader.add_option(
572 '--resize-buffer',
573 action='store_false', dest='noresizebuffer',
574 help='The buffer size is automatically resized from an initial value of --buffer-size (default)')
575 downloader.add_option(
576 '--no-resize-buffer',
577 action='store_true', dest='noresizebuffer', default=False,
578 help='Do not automatically adjust the buffer size')
579 downloader.add_option(
580 '--http-chunk-size',
581 dest='http_chunk_size', metavar='SIZE', default=None,
582 help=(
583 'Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
584 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)'))
585 downloader.add_option(
586 '--test',
587 action='store_true', dest='test', default=False,
588 help=optparse.SUPPRESS_HELP)
589 downloader.add_option(
590 '--playlist-reverse',
591 action='store_true',
592 help='Download playlist videos in reverse order')
593 downloader.add_option(
594 '--no-playlist-reverse',
595 action='store_false', dest='playlist_reverse',
596 help='Download playlist videos in default order (default)')
597 downloader.add_option(
598 '--playlist-random',
599 action='store_true',
600 help='Download playlist videos in random order')
601 downloader.add_option(
602 '--xattr-set-filesize',
603 dest='xattr_set_filesize', action='store_true',
604 help='Set file xattribute ytdl.filesize with expected file size')
605 downloader.add_option(
606 '--hls-prefer-native',
607 dest='hls_prefer_native', action='store_true', default=None,
608 help='Use the native HLS downloader instead of ffmpeg')
609 downloader.add_option(
610 '--hls-prefer-ffmpeg',
611 dest='hls_prefer_native', action='store_false', default=None,
612 help='Use ffmpeg instead of the native HLS downloader')
613 downloader.add_option(
614 '--hls-use-mpegts',
615 dest='hls_use_mpegts', action='store_true',
616 help=(
617 'Use the mpegts container for HLS videos, allowing to play the '
618 'video while downloading (some players may not be able to play it)'))
619 downloader.add_option(
620 '--external-downloader',
621 dest='external_downloader', metavar='COMMAND',
622 help=(
623 'Use the specified external downloader. '
624 'Currently supports %s' % ','.join(list_external_downloaders())))
625 downloader.add_option(
626 '--external-downloader-args',
627 dest='external_downloader_args', metavar='ARGS',
628 help='Give these arguments to the external downloader')
629
630 workarounds = optparse.OptionGroup(parser, 'Workarounds')
631 workarounds.add_option(
632 '--encoding',
633 dest='encoding', metavar='ENCODING',
634 help='Force the specified encoding (experimental)')
635 workarounds.add_option(
636 '--no-check-certificate',
637 action='store_true', dest='no_check_certificate', default=False,
638 help='Suppress HTTPS certificate validation')
639 workarounds.add_option(
640 '--prefer-insecure', '--prefer-unsecure',
641 action='store_true', dest='prefer_insecure',
642 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
643 workarounds.add_option(
644 '--user-agent',
645 metavar='UA', dest='user_agent',
646 help='Specify a custom user agent')
647 workarounds.add_option(
648 '--referer',
649 metavar='URL', dest='referer', default=None,
650 help='Specify a custom referer, use if the video access is restricted to one domain',
651 )
652 workarounds.add_option(
653 '--add-header',
654 metavar='FIELD:VALUE', dest='headers', action='append',
655 help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
656 )
657 workarounds.add_option(
658 '--bidi-workaround',
659 dest='bidi_workaround', action='store_true',
660 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
661 workarounds.add_option(
662 '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
663 dest='sleep_interval', type=float,
664 help=(
665 'Number of seconds to sleep before each download when used alone '
666 'or a lower bound of a range for randomized sleep before each download '
667 '(minimum possible number of seconds to sleep) when used along with '
668 '--max-sleep-interval.'))
669 workarounds.add_option(
670 '--max-sleep-interval', metavar='SECONDS',
671 dest='max_sleep_interval', type=float,
672 help=(
673 'Upper bound of a range for randomized sleep before each download '
674 '(maximum possible number of seconds to sleep). Must only be used '
675 'along with --min-sleep-interval.'))
676 workarounds.add_option(
677 '--sleep-subtitles', metavar='SECONDS',
678 dest='sleep_interval_subtitles', default=0, type=int,
679 help='Enforce sleep interval on subtitles as well')
680
681 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
682 verbosity.add_option(
683 '-q', '--quiet',
684 action='store_true', dest='quiet', default=False,
685 help='Activate quiet mode')
686 verbosity.add_option(
687 '--no-warnings',
688 dest='no_warnings', action='store_true', default=False,
689 help='Ignore warnings')
690 verbosity.add_option(
691 '-s', '--simulate',
692 action='store_true', dest='simulate', default=False,
693 help='Do not download the video and do not write anything to disk')
694 verbosity.add_option(
695 '--skip-download', '--no-download',
696 action='store_true', dest='skip_download', default=False,
697 help='Do not download the video')
698 verbosity.add_option(
699 '-g', '--get-url',
700 action='store_true', dest='geturl', default=False,
701 help='Simulate, quiet but print URL')
702 verbosity.add_option(
703 '-e', '--get-title',
704 action='store_true', dest='gettitle', default=False,
705 help='Simulate, quiet but print title')
706 verbosity.add_option(
707 '--get-id',
708 action='store_true', dest='getid', default=False,
709 help='Simulate, quiet but print id')
710 verbosity.add_option(
711 '--get-thumbnail',
712 action='store_true', dest='getthumbnail', default=False,
713 help='Simulate, quiet but print thumbnail URL')
714 verbosity.add_option(
715 '--get-description',
716 action='store_true', dest='getdescription', default=False,
717 help='Simulate, quiet but print video description')
718 verbosity.add_option(
719 '--get-duration',
720 action='store_true', dest='getduration', default=False,
721 help='Simulate, quiet but print video length')
722 verbosity.add_option(
723 '--get-filename',
724 action='store_true', dest='getfilename', default=False,
725 help='Simulate, quiet but print output filename')
726 verbosity.add_option(
727 '--get-format',
728 action='store_true', dest='getformat', default=False,
729 help='Simulate, quiet but print output format')
730 verbosity.add_option(
731 '-j', '--dump-json',
732 action='store_true', dest='dumpjson', default=False,
733 help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.')
734 verbosity.add_option(
735 '-J', '--dump-single-json',
736 action='store_true', dest='dump_single_json', default=False,
737 help=(
738 'Simulate, quiet but print JSON information for each command-line argument. '
739 'If the URL refers to a playlist, dump the whole playlist information in a single line.'))
740 verbosity.add_option(
741 '--print-json',
742 action='store_true', dest='print_json', default=False,
743 help='Be quiet and print the video information as JSON (video is still being downloaded).')
744 verbosity.add_option(
745 '--force-write-archive', '--force-write-download-archive', '--force-download-archive',
746 action='store_true', dest='force_write_download_archive', default=False,
747 help=(
748 'Force download archive entries to be written as far as no errors occur,'
749 'even if -s or another simulation switch is used.'))
750 verbosity.add_option(
751 '--newline',
752 action='store_true', dest='progress_with_newline', default=False,
753 help='Output progress bar as new lines')
754 verbosity.add_option(
755 '--no-progress',
756 action='store_true', dest='noprogress', default=False,
757 help='Do not print progress bar')
758 verbosity.add_option(
759 '--console-title',
760 action='store_true', dest='consoletitle', default=False,
761 help='Display progress in console titlebar')
762 verbosity.add_option(
763 '-v', '--verbose',
764 action='store_true', dest='verbose', default=False,
765 help='Print various debugging information')
766 verbosity.add_option(
767 '--dump-pages', '--dump-intermediate-pages',
768 action='store_true', dest='dump_intermediate_pages', default=False,
769 help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
770 verbosity.add_option(
771 '--write-pages',
772 action='store_true', dest='write_pages', default=False,
773 help='Write downloaded intermediary pages to files in the current directory to debug problems')
774 verbosity.add_option(
775 '--youtube-print-sig-code',
776 action='store_true', dest='youtube_print_sig_code', default=False,
777 help=optparse.SUPPRESS_HELP)
778 verbosity.add_option(
779 '--print-traffic', '--dump-headers',
780 dest='debug_printtraffic', action='store_true', default=False,
781 help='Display sent and read HTTP traffic')
782 verbosity.add_option(
783 '-C', '--call-home',
784 dest='call_home', action='store_true', default=False,
785 help='[Broken] Contact the youtube-dlc server for debugging')
786 verbosity.add_option(
787 '--no-call-home',
788 dest='call_home', action='store_false',
789 help='Do not contact the youtube-dlc server for debugging (default)')
790
791 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
792 filesystem.add_option(
793 '-a', '--batch-file',
794 dest='batchfile', metavar='FILE',
795 help="File containing URLs to download ('-' for stdin), one URL per line. "
796 "Lines starting with '#', ';' or ']' are considered as comments and ignored.")
797 filesystem.add_option(
798 '--id', default=False,
799 action='store_true', dest='useid', help=optparse.SUPPRESS_HELP)
800 filesystem.add_option(
801 '-o', '--output',
802 dest='outtmpl', metavar='TEMPLATE',
803 help='Output filename template, see the "OUTPUT TEMPLATE" for details')
804 filesystem.add_option(
805 '--autonumber-size',
806 dest='autonumber_size', metavar='NUMBER', type=int,
807 help=optparse.SUPPRESS_HELP)
808 filesystem.add_option(
809 '--autonumber-start',
810 dest='autonumber_start', metavar='NUMBER', default=1, type=int,
811 help='Specify the start value for %(autonumber)s (default is %default)')
812 filesystem.add_option(
813 '--restrict-filenames',
814 action='store_true', dest='restrictfilenames', default=False,
815 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
816 filesystem.add_option(
817 '--no-restrict-filenames',
818 action='store_false', dest='restrictfilenames', default=False,
819 help='Allow Unicode characters, "&" and spaces in filenames (default)')
820 filesystem.add_option(
821 '-A', '--auto-number',
822 action='store_true', dest='autonumber', default=False,
823 help=optparse.SUPPRESS_HELP)
824 filesystem.add_option(
825 '-t', '--title',
826 action='store_true', dest='usetitle', default=False,
827 help=optparse.SUPPRESS_HELP)
828 filesystem.add_option(
829 '-l', '--literal', default=False,
830 action='store_true', dest='usetitle',
831 help=optparse.SUPPRESS_HELP)
832 filesystem.add_option(
833 '-w', '--no-overwrites',
834 action='store_false', dest='overwrites', default=None,
835 help='Do not overwrite any files')
836 filesystem.add_option(
837 '--force-overwrites', '--yes-overwrites',
838 action='store_true', dest='overwrites',
839 help='Overwrite all video and metadata files. This option includes --no-continue')
840 filesystem.add_option(
841 '--no-force-overwrites',
842 action='store_const', dest='overwrites', const=None,
843 help='Do not overwrite the video, but overwrite related files (default)')
844 filesystem.add_option(
845 '-c', '--continue',
846 action='store_true', dest='continue_dl', default=True,
847 help='Resume partially downloaded files (default)')
848 filesystem.add_option(
849 '--no-continue',
850 action='store_false', dest='continue_dl',
851 help='Restart download of partially downloaded files from beginning')
852 filesystem.add_option(
853 '--part',
854 action='store_false', dest='nopart', default=False,
855 help='Use .part files instead of writing directly into output file (default)')
856 filesystem.add_option(
857 '--no-part',
858 action='store_true', dest='nopart',
859 help='Do not use .part files - write directly into output file')
860 filesystem.add_option(
861 '--mtime',
862 action='store_true', dest='updatetime', default=True,
863 help='Use the Last-modified header to set the file modification time (default)')
864 filesystem.add_option(
865 '--no-mtime',
866 action='store_false', dest='updatetime',
867 help='Do not use the Last-modified header to set the file modification time')
868 filesystem.add_option(
869 '--write-description',
870 action='store_true', dest='writedescription', default=False,
871 help='Write video description to a .description file')
872 filesystem.add_option(
873 '--no-write-description',
874 action='store_false', dest='writedescription',
875 help='Do not write video description (default)')
876 filesystem.add_option(
877 '--write-info-json',
878 action='store_true', dest='writeinfojson', default=False,
879 help='Write video metadata to a .info.json file')
880 filesystem.add_option(
881 '--no-write-info-json',
882 action='store_false', dest='writeinfojson',
883 help='Do not write video metadata (default)')
884 filesystem.add_option(
885 '--write-annotations',
886 action='store_true', dest='writeannotations', default=False,
887 help='Write video annotations to a .annotations.xml file')
888 filesystem.add_option(
889 '--no-write-annotations',
890 action='store_false', dest='writeannotations',
891 help='Do not write video annotations (default)')
892 filesystem.add_option(
893 '--load-info-json', '--load-info',
894 dest='load_info_filename', metavar='FILE',
895 help='JSON file containing the video information (created with the "--write-info-json" option)')
896 filesystem.add_option(
897 '--cookies',
898 dest='cookiefile', metavar='FILE',
899 help='File to read cookies from and dump cookie jar in')
900 filesystem.add_option(
901 '--no-cookies',
902 action='store_const', const=None, dest='cookiefile', metavar='FILE',
903 help='Do not read/dump cookies (default)')
904 filesystem.add_option(
905 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
906 help='Location in the filesystem where youtube-dl can store some downloaded information permanently. By default $XDG_CACHE_HOME/youtube-dl or ~/.cache/youtube-dl . At the moment, only YouTube player files (for videos with obfuscated signatures) are cached, but that may change.')
907 filesystem.add_option(
908 '--no-cache-dir', action='store_false', dest='cachedir',
909 help='Disable filesystem caching')
910 filesystem.add_option(
911 '--rm-cache-dir',
912 action='store_true', dest='rm_cachedir',
913 help='Delete all filesystem cache files')
914 filesystem.add_option(
915 '--trim-file-name', metavar='LENGTH',
916 dest='trim_file_name', default=0, type=int,
917 help='Limit the filename length (extension excluded)')
918
919 thumbnail = optparse.OptionGroup(parser, 'Thumbnail Images')
920 thumbnail.add_option(
921 '--write-thumbnail',
922 action='store_true', dest='writethumbnail', default=False,
923 help='Write thumbnail image to disk')
924 thumbnail.add_option(
925 '--no-write-thumbnail',
926 action='store_false', dest='writethumbnail',
927 help='Do not write thumbnail image to disk (default)')
928 thumbnail.add_option(
929 '--write-all-thumbnails',
930 action='store_true', dest='write_all_thumbnails', default=False,
931 help='Write all thumbnail image formats to disk')
932 thumbnail.add_option(
933 '--list-thumbnails',
934 action='store_true', dest='list_thumbnails', default=False,
935 help='Simulate and list all available thumbnail formats')
936
937 link = optparse.OptionGroup(parser, 'Internet Shortcut Options')
938 link.add_option(
939 '--write-link',
940 action='store_true', dest='writelink', default=False,
941 help='Write an internet shortcut file, depending on the current platform (.url/.webloc/.desktop). The URL may be cached by the OS.')
942 link.add_option(
943 '--write-url-link',
944 action='store_true', dest='writeurllink', default=False,
945 help='Write a Windows internet shortcut file (.url). Note that the OS caches the URL based on the file path.')
946 link.add_option(
947 '--write-webloc-link',
948 action='store_true', dest='writewebloclink', default=False,
949 help='Write a macOS internet shortcut file (.webloc)')
950 link.add_option(
951 '--write-desktop-link',
952 action='store_true', dest='writedesktoplink', default=False,
953 help='Write a Linux internet shortcut file (.desktop)')
954
955 postproc = optparse.OptionGroup(parser, 'Post-Processing Options')
956 postproc.add_option(
957 '-x', '--extract-audio',
958 action='store_true', dest='extractaudio', default=False,
959 help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
960 postproc.add_option(
961 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
962 help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
963 postproc.add_option(
964 '--audio-quality', metavar='QUALITY',
965 dest='audioquality', default='5',
966 help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
967 postproc.add_option(
968 '--remux-video',
969 metavar='FORMAT', dest='remuxvideo', default=None,
970 help=(
971 'Remux the video into another container if necessary (currently supported: mp4|mkv). '
972 'If target container does not support the video/audio codec, remuxing will fail'))
973 postproc.add_option(
974 '--recode-video',
975 metavar='FORMAT', dest='recodevideo', default=None,
976 help='Re-encode the video into another format if re-encoding is necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
977 postproc.add_option(
978 '--postprocessor-args', metavar='NAME:ARGS',
979 dest='postprocessor_args', action='append',
980 help=(
981 'Give these arguments to the postprocessors. '
982 "Specify the postprocessor name and the arguments separated by a colon ':' "
983 'to give the argument to only the specified postprocessor. Supported names are '
984 'ExtractAudio, VideoRemuxer, VideoConvertor, EmbedSubtitle, Metadata, Merger, FixupStretched, '
985 'FixupM4a, FixupM3u8, SubtitlesConvertor, EmbedThumbnail, XAttrMetadata, SponSkrub and Default. '
986 'You can use this option multiple times to give different arguments to different postprocessors'))
987 postproc.add_option(
988 '-k', '--keep-video',
989 action='store_true', dest='keepvideo', default=False,
990 help='Keep the intermediate video file on disk after post-processing')
991 postproc.add_option(
992 '--no-keep-video',
993 action='store_false', dest='keepvideo',
994 help='Delete the intermediate video file after post-processing (default)')
995 postproc.add_option(
996 '--post-overwrites',
997 action='store_false', dest='nopostoverwrites',
998 help='Overwrite post-processed files (default)')
999 postproc.add_option(
1000 '--no-post-overwrites',
1001 action='store_true', dest='nopostoverwrites', default=False,
1002 help='Do not overwrite post-processed files')
1003 postproc.add_option(
1004 '--embed-subs',
1005 action='store_true', dest='embedsubtitles', default=False,
1006 help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
1007 postproc.add_option(
1008 '--no-embed-subs',
1009 action='store_false', dest='embedsubtitles',
1010 help='Do not embed subtitles (default)')
1011 postproc.add_option(
1012 '--embed-thumbnail',
1013 action='store_true', dest='embedthumbnail', default=False,
1014 help='Embed thumbnail in the audio as cover art')
1015 postproc.add_option(
1016 '--no-embed-thumbnail',
1017 action='store_false', dest='embedthumbnail',
1018 help='Do not embed thumbnail (default)')
1019 postproc.add_option(
1020 '--add-metadata',
1021 action='store_true', dest='addmetadata', default=False,
1022 help='Write metadata to the video file')
1023 postproc.add_option(
1024 '--no-add-metadata',
1025 action='store_false', dest='addmetadata',
1026 help='Do not write metadata (default)')
1027 postproc.add_option(
1028 '--metadata-from-title',
1029 metavar='FORMAT', dest='metafromtitle',
1030 help=(
1031 'Parse additional metadata like song title / artist from the video title. '
1032 'The format syntax is the same as --output. Regular expression with '
1033 'named capture groups may also be used. '
1034 'The parsed parameters replace existing values. '
1035 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
1036 '"Coldplay - Paradise". '
1037 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"'))
1038 postproc.add_option(
1039 '--xattrs',
1040 action='store_true', dest='xattrs', default=False,
1041 help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
1042 postproc.add_option(
1043 '--fixup',
1044 metavar='POLICY', dest='fixup', default='detect_or_warn',
1045 help=(
1046 'Automatically correct known faults of the file. '
1047 'One of never (do nothing), warn (only emit a warning), '
1048 'detect_or_warn (the default; fix file if we can, warn otherwise)'))
1049 postproc.add_option(
1050 '--prefer-avconv', '--no-prefer-ffmpeg',
1051 action='store_false', dest='prefer_ffmpeg',
1052 help='Prefer avconv over ffmpeg for running the postprocessors')
1053 postproc.add_option(
1054 '--prefer-ffmpeg', '--no-prefer-avconv',
1055 action='store_true', dest='prefer_ffmpeg',
1056 help='Prefer ffmpeg over avconv for running the postprocessors (default)')
1057 postproc.add_option(
1058 '--ffmpeg-location', '--avconv-location', metavar='PATH',
1059 dest='ffmpeg_location',
1060 help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
1061 postproc.add_option(
1062 '--exec',
1063 metavar='CMD', dest='exec_cmd',
1064 help='Execute a command on the file after downloading and post-processing, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
1065 postproc.add_option(
1066 '--convert-subs', '--convert-subtitles',
1067 metavar='FORMAT', dest='convertsubtitles', default=None,
1068 help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
1069
1070 sponskrub = optparse.OptionGroup(parser, 'SponSkrub Options (SponsorBlock)')
1071 sponskrub.add_option(
1072 '--sponskrub',
1073 action='store_true', dest='sponskrub', default=None,
1074 help=(
1075 'Use sponskrub to mark sponsored sections with the data available in SponsorBlock API. '
1076 'This is enabled by default if the sponskrub binary exists (Youtube only)'))
1077 sponskrub.add_option(
1078 '--no-sponskrub',
1079 action='store_false', dest='sponskrub',
1080 help='Do not use sponskrub')
1081 sponskrub.add_option(
1082 '--sponskrub-cut', default=False,
1083 action='store_true', dest='sponskrub_cut',
1084 help='Cut out the sponsor sections instead of simply marking them')
1085 sponskrub.add_option(
1086 '--no-sponskrub-cut',
1087 action='store_false', dest='sponskrub_cut',
1088 help='Simply mark the sponsor sections, not cut them out (default)')
1089 sponskrub.add_option(
1090 '--sponskrub-force', default=False,
1091 action='store_true', dest='sponskrub_force',
1092 help='Run sponskrub even if the video was already downloaded')
1093 sponskrub.add_option(
1094 '--no-sponskrub-force',
1095 action='store_true', dest='sponskrub_force',
1096 help='Do not cut out the sponsor sections if the video was already downloaded (default)')
1097 sponskrub.add_option(
1098 '--sponskrub-location', metavar='PATH',
1099 dest='sponskrub_path', default='',
1100 help='Location of the sponskrub binary; either the path to the binary or its containing directory.')
1101 sponskrub.add_option(
1102 '--sponskrub-args', dest='sponskrub_args', metavar='ARGS',
1103 help=optparse.SUPPRESS_HELP)
1104
1105 extractor = optparse.OptionGroup(parser, 'Extractor Options')
1106 extractor.add_option(
1107 '--allow-dynamic-mpd', '--no-ignore-dynamic-mpd',
1108 action='store_true', dest='dynamic_mpd', default=True,
1109 help='Process dynamic DASH manifests (default)')
1110 extractor.add_option(
1111 '--ignore-dynamic-mpd', '--no-allow-dynamic-mpd',
1112 action='store_false', dest='dynamic_mpd',
1113 help='Do not process dynamic DASH manifests')
1114
1115 parser.add_option_group(general)
1116 parser.add_option_group(network)
1117 parser.add_option_group(geo)
1118 parser.add_option_group(selection)
1119 parser.add_option_group(downloader)
1120 parser.add_option_group(filesystem)
1121 parser.add_option_group(thumbnail)
1122 parser.add_option_group(link)
1123 parser.add_option_group(verbosity)
1124 parser.add_option_group(workarounds)
1125 parser.add_option_group(video_format)
1126 parser.add_option_group(subtitles)
1127 parser.add_option_group(authentication)
1128 parser.add_option_group(adobe_pass)
1129 parser.add_option_group(postproc)
1130 parser.add_option_group(sponskrub)
1131 parser.add_option_group(extractor)
1132
1133 if overrideArguments is not None:
1134 opts, args = parser.parse_args(overrideArguments)
1135 if opts.verbose:
1136 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
1137 else:
1138 def compat_conf(conf):
1139 if sys.version_info < (3,):
1140 return [a.decode(preferredencoding(), 'replace') for a in conf]
1141 return conf
1142
1143 configs = {
1144 'command_line': compat_conf(sys.argv[1:]),
1145 'custom': [], 'portable': [], 'user': [], 'system': []}
1146 opts, args = parser.parse_args(configs['command_line'])
1147
1148 def get_configs():
1149 if '--config-location' in configs['command_line']:
1150 location = compat_expanduser(opts.config_location)
1151 if os.path.isdir(location):
1152 location = os.path.join(location, 'youtube-dlc.conf')
1153 if not os.path.exists(location):
1154 parser.error('config-location %s does not exist.' % location)
1155 configs['custom'] = _readOptions(location)
1156
1157 if '--ignore-config' in configs['command_line']:
1158 return
1159 if '--ignore-config' in configs['custom']:
1160 return
1161
1162 def get_portable_path():
1163 path = os.path.dirname(sys.argv[0])
1164 if os.path.abspath(sys.argv[0]) != os.path.abspath(sys.executable): # Not packaged
1165 path = os.path.join(path, '..')
1166 return os.path.abspath(path)
1167
1168 run_path = get_portable_path()
1169 configs['portable'] = _readOptions(os.path.join(run_path, 'yt-dlp.conf'), default=None)
1170 if configs['portable'] is None:
1171 configs['portable'] = _readOptions(os.path.join(run_path, 'youtube-dlc.conf'))
1172
1173 if '--ignore-config' in configs['portable']:
1174 return
1175 configs['system'] = _readOptions('/etc/yt-dlp.conf', default=None)
1176 if configs['system'] is None:
1177 configs['system'] = _readOptions('/etc/youtube-dlc.conf')
1178
1179 if '--ignore-config' in configs['system']:
1180 return
1181 configs['user'] = _readUserConf('yt-dlp', default=None)
1182 if configs['user'] is None:
1183 configs['user'] = _readUserConf('youtube-dlc')
1184 if '--ignore-config' in configs['user']:
1185 configs['system'] = []
1186
1187 get_configs()
1188 argv = configs['system'] + configs['user'] + configs['portable'] + configs['custom'] + configs['command_line']
1189 opts, args = parser.parse_args(argv)
1190 if opts.verbose:
1191 for conf_label, conf in (
1192 ('System config', configs['system']),
1193 ('User config', configs['user']),
1194 ('Portable config', configs['portable']),
1195 ('Custom config', configs['custom']),
1196 ('Command-line args', configs['command_line'])):
1197 write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
1198
1199 return parser, opts, args