]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/options.py
Initiate new release.
[youtubedl] / youtube_dl / 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():
58 xdg_config_home = compat_getenv('XDG_CONFIG_HOME')
59 if xdg_config_home:
60 userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
61 if not os.path.isfile(userConfFile):
62 userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
63 else:
64 userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')
65 if not os.path.isfile(userConfFile):
66 userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')
67 userConf = _readOptions(userConfFile, None)
68
69 if userConf is None:
70 appdata_dir = compat_getenv('appdata')
71 if appdata_dir:
72 userConf = _readOptions(
73 os.path.join(appdata_dir, 'youtube-dl', 'config'),
74 default=None)
75 if userConf is None:
76 userConf = _readOptions(
77 os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
78 default=None)
79
80 if userConf is None:
81 userConf = _readOptions(
82 os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),
83 default=None)
84 if userConf is None:
85 userConf = _readOptions(
86 os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),
87 default=None)
88
89 if userConf is None:
90 userConf = []
91
92 return userConf
93
94 def _format_option_string(option):
95 ''' ('-o', '--option') -> -o, --format METAVAR'''
96
97 opts = []
98
99 if option._short_opts:
100 opts.append(option._short_opts[0])
101 if option._long_opts:
102 opts.append(option._long_opts[0])
103 if len(opts) > 1:
104 opts.insert(1, ', ')
105
106 if option.takes_value():
107 opts.append(' %s' % option.metavar)
108
109 return ''.join(opts)
110
111 def _comma_separated_values_options_callback(option, opt_str, value, parser):
112 setattr(parser.values, option.dest, value.split(','))
113
114 # No need to wrap help messages if we're on a wide console
115 columns = compat_get_terminal_size().columns
116 max_width = columns if columns else 80
117 max_help_position = 80
118
119 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
120 fmt.format_option_strings = _format_option_string
121
122 kw = {
123 'version': __version__,
124 'formatter': fmt,
125 'usage': '%prog [OPTIONS] URL [URL...]',
126 'conflict_handler': 'resolve',
127 }
128
129 parser = optparse.OptionParser(**compat_kwargs(kw))
130
131 general = optparse.OptionGroup(parser, 'General Options')
132 general.add_option(
133 '-h', '--help',
134 action='help',
135 help='Print this help text and exit')
136 general.add_option(
137 '--version',
138 action='version',
139 help='Print program version and exit')
140 general.add_option(
141 '-U', '--update',
142 action='store_true', dest='update_self',
143 help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
144 general.add_option(
145 '-i', '--ignore-errors',
146 action='store_true', dest='ignoreerrors', default=False,
147 help='Continue on download errors, for example to skip unavailable videos in a playlist')
148 general.add_option(
149 '--abort-on-error',
150 action='store_false', dest='ignoreerrors',
151 help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
152 general.add_option(
153 '--dump-user-agent',
154 action='store_true', dest='dump_user_agent', default=False,
155 help='Display the current browser identification')
156 general.add_option(
157 '--list-extractors',
158 action='store_true', dest='list_extractors', default=False,
159 help='List all supported extractors')
160 general.add_option(
161 '--extractor-descriptions',
162 action='store_true', dest='list_extractor_descriptions', default=False,
163 help='Output descriptions of all supported extractors')
164 general.add_option(
165 '--force-generic-extractor',
166 action='store_true', dest='force_generic_extractor', default=False,
167 help='Force extraction to use the generic extractor')
168 general.add_option(
169 '--default-search',
170 dest='default_search', metavar='PREFIX',
171 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.')
172 general.add_option(
173 '--ignore-config',
174 action='store_true',
175 help='Do not read configuration files. '
176 'When given in the global configuration file /etc/youtube-dl.conf: '
177 'Do not read the user configuration in ~/.config/youtube-dl/config '
178 '(%APPDATA%/youtube-dl/config.txt on Windows)')
179 general.add_option(
180 '--config-location',
181 dest='config_location', metavar='PATH',
182 help='Location of the configuration file; either the path to the config or its containing directory.')
183 general.add_option(
184 '--flat-playlist',
185 action='store_const', dest='extract_flat', const='in_playlist',
186 default=False,
187 help='Do not extract the videos of a playlist, only list them.')
188 general.add_option(
189 '--mark-watched',
190 action='store_true', dest='mark_watched', default=False,
191 help='Mark videos watched (YouTube only)')
192 general.add_option(
193 '--no-mark-watched',
194 action='store_false', dest='mark_watched', default=False,
195 help='Do not mark videos watched (YouTube only)')
196 general.add_option(
197 '--no-color', '--no-colors',
198 action='store_true', dest='no_color',
199 default=False,
200 help='Do not emit color codes in output')
201
202 network = optparse.OptionGroup(parser, 'Network Options')
203 network.add_option(
204 '--proxy', dest='proxy',
205 default=None, metavar='URL',
206 help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable '
207 'SOCKS proxy, specify a proper scheme. For example '
208 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
209 'for direct connection')
210 network.add_option(
211 '--socket-timeout',
212 dest='socket_timeout', type=float, default=None, metavar='SECONDS',
213 help='Time to wait before giving up, in seconds')
214 network.add_option(
215 '--source-address',
216 metavar='IP', dest='source_address', default=None,
217 help='Client-side IP address to bind to',
218 )
219 network.add_option(
220 '-4', '--force-ipv4',
221 action='store_const', const='0.0.0.0', dest='source_address',
222 help='Make all connections via IPv4',
223 )
224 network.add_option(
225 '-6', '--force-ipv6',
226 action='store_const', const='::', dest='source_address',
227 help='Make all connections via IPv6',
228 )
229
230 geo = optparse.OptionGroup(parser, 'Geo Restriction')
231 geo.add_option(
232 '--geo-verification-proxy',
233 dest='geo_verification_proxy', default=None, metavar='URL',
234 help='Use this proxy to verify the IP address for some geo-restricted sites. '
235 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.')
236 geo.add_option(
237 '--cn-verification-proxy',
238 dest='cn_verification_proxy', default=None, metavar='URL',
239 help=optparse.SUPPRESS_HELP)
240 geo.add_option(
241 '--geo-bypass',
242 action='store_true', dest='geo_bypass', default=True,
243 help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')
244 geo.add_option(
245 '--no-geo-bypass',
246 action='store_false', dest='geo_bypass', default=True,
247 help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
248 geo.add_option(
249 '--geo-bypass-country', metavar='CODE',
250 dest='geo_bypass_country', default=None,
251 help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
252 geo.add_option(
253 '--geo-bypass-ip-block', metavar='IP_BLOCK',
254 dest='geo_bypass_ip_block', default=None,
255 help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
256
257 selection = optparse.OptionGroup(parser, 'Video Selection')
258 selection.add_option(
259 '--playlist-start',
260 dest='playliststart', metavar='NUMBER', default=1, type=int,
261 help='Playlist video to start at (default is %default)')
262 selection.add_option(
263 '--playlist-end',
264 dest='playlistend', metavar='NUMBER', default=None, type=int,
265 help='Playlist video to end at (default is last)')
266 selection.add_option(
267 '--playlist-items',
268 dest='playlist_items', metavar='ITEM_SPEC', default=None,
269 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.')
270 selection.add_option(
271 '--match-title',
272 dest='matchtitle', metavar='REGEX',
273 help='Download only matching titles (regex or caseless sub-string)')
274 selection.add_option(
275 '--reject-title',
276 dest='rejecttitle', metavar='REGEX',
277 help='Skip download for matching titles (regex or caseless sub-string)')
278 selection.add_option(
279 '--max-downloads',
280 dest='max_downloads', metavar='NUMBER', type=int, default=None,
281 help='Abort after downloading NUMBER files')
282 selection.add_option(
283 '--min-filesize',
284 metavar='SIZE', dest='min_filesize', default=None,
285 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
286 selection.add_option(
287 '--max-filesize',
288 metavar='SIZE', dest='max_filesize', default=None,
289 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
290 selection.add_option(
291 '--date',
292 metavar='DATE', dest='date', default=None,
293 help='Download only videos uploaded in this date')
294 selection.add_option(
295 '--datebefore',
296 metavar='DATE', dest='datebefore', default=None,
297 help='Download only videos uploaded on or before this date (i.e. inclusive)')
298 selection.add_option(
299 '--dateafter',
300 metavar='DATE', dest='dateafter', default=None,
301 help='Download only videos uploaded on or after this date (i.e. inclusive)')
302 selection.add_option(
303 '--min-views',
304 metavar='COUNT', dest='min_views', default=None, type=int,
305 help='Do not download any videos with less than COUNT views')
306 selection.add_option(
307 '--max-views',
308 metavar='COUNT', dest='max_views', default=None, type=int,
309 help='Do not download any videos with more than COUNT views')
310 selection.add_option(
311 '--match-filter',
312 metavar='FILTER', dest='match_filter', default=None,
313 help=(
314 'Generic video filter. '
315 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to '
316 'match if the key is present, '
317 '!key to check if the key is not present, '
318 'key > NUMBER (like "comment_count > 12", also works with '
319 '>=, <, <=, !=, =) to compare against a number, '
320 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
321 'to match against a string literal '
322 'and & to require multiple matches. '
323 'Values which are not known are excluded unless you '
324 'put a question mark (?) after the operator. '
325 'For example, to only match videos that have been liked more than '
326 '100 times and disliked less than 50 times (or the dislike '
327 'functionality is not available at the given service), but who '
328 'also have a description, use --match-filter '
329 '"like_count > 100 & dislike_count <? 50 & description" .'
330 ))
331 selection.add_option(
332 '--no-playlist',
333 action='store_true', dest='noplaylist', default=False,
334 help='Download only the video, if the URL refers to a video and a playlist.')
335 selection.add_option(
336 '--yes-playlist',
337 action='store_false', dest='noplaylist', default=False,
338 help='Download the playlist, if the URL refers to a video and a playlist.')
339 selection.add_option(
340 '--age-limit',
341 metavar='YEARS', dest='age_limit', default=None, type=int,
342 help='Download only videos suitable for the given age')
343 selection.add_option(
344 '--download-archive', metavar='FILE',
345 dest='download_archive',
346 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
347 selection.add_option(
348 '--include-ads',
349 dest='include_ads', action='store_true',
350 help='Download advertisements as well (experimental)')
351
352 authentication = optparse.OptionGroup(parser, 'Authentication Options')
353 authentication.add_option(
354 '-u', '--username',
355 dest='username', metavar='USERNAME',
356 help='Login with this account ID')
357 authentication.add_option(
358 '-p', '--password',
359 dest='password', metavar='PASSWORD',
360 help='Account password. If this option is left out, youtube-dl will ask interactively.')
361 authentication.add_option(
362 '-2', '--twofactor',
363 dest='twofactor', metavar='TWOFACTOR',
364 help='Two-factor authentication code')
365 authentication.add_option(
366 '-n', '--netrc',
367 action='store_true', dest='usenetrc', default=False,
368 help='Use .netrc authentication data')
369 authentication.add_option(
370 '--video-password',
371 dest='videopassword', metavar='PASSWORD',
372 help='Video password (vimeo, smotri, youku)')
373
374 adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
375 adobe_pass.add_option(
376 '--ap-mso',
377 dest='ap_mso', metavar='MSO',
378 help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
379 adobe_pass.add_option(
380 '--ap-username',
381 dest='ap_username', metavar='USERNAME',
382 help='Multiple-system operator account login')
383 adobe_pass.add_option(
384 '--ap-password',
385 dest='ap_password', metavar='PASSWORD',
386 help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.')
387 adobe_pass.add_option(
388 '--ap-list-mso',
389 action='store_true', dest='ap_list_mso', default=False,
390 help='List all supported multiple-system operators')
391
392 video_format = optparse.OptionGroup(parser, 'Video Format Options')
393 video_format.add_option(
394 '-f', '--format',
395 action='store', dest='format', metavar='FORMAT', default=None,
396 help='Video format code, see the "FORMAT SELECTION" for all the info')
397 video_format.add_option(
398 '--all-formats',
399 action='store_const', dest='format', const='all',
400 help='Download all available video formats')
401 video_format.add_option(
402 '--prefer-free-formats',
403 action='store_true', dest='prefer_free_formats', default=False,
404 help='Prefer free video formats unless a specific one is requested')
405 video_format.add_option(
406 '-F', '--list-formats',
407 action='store_true', dest='listformats',
408 help='List all available formats of requested videos')
409 video_format.add_option(
410 '--youtube-include-dash-manifest',
411 action='store_true', dest='youtube_include_dash_manifest', default=True,
412 help=optparse.SUPPRESS_HELP)
413 video_format.add_option(
414 '--youtube-skip-dash-manifest',
415 action='store_false', dest='youtube_include_dash_manifest',
416 help='Do not download the DASH manifests and related data on YouTube videos')
417 video_format.add_option(
418 '--merge-output-format',
419 action='store', dest='merge_output_format', metavar='FORMAT', default=None,
420 help=(
421 'If a merge is required (e.g. bestvideo+bestaudio), '
422 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
423 'Ignored if no merge is required'))
424
425 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
426 subtitles.add_option(
427 '--write-sub', '--write-srt',
428 action='store_true', dest='writesubtitles', default=False,
429 help='Write subtitle file')
430 subtitles.add_option(
431 '--write-auto-sub', '--write-automatic-sub',
432 action='store_true', dest='writeautomaticsub', default=False,
433 help='Write automatically generated subtitle file (YouTube only)')
434 subtitles.add_option(
435 '--all-subs',
436 action='store_true', dest='allsubtitles', default=False,
437 help='Download all the available subtitles of the video')
438 subtitles.add_option(
439 '--list-subs',
440 action='store_true', dest='listsubtitles', default=False,
441 help='List all available subtitles for the video')
442 subtitles.add_option(
443 '--sub-format',
444 action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
445 help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
446 subtitles.add_option(
447 '--sub-lang', '--sub-langs', '--srt-lang',
448 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
449 default=[], callback=_comma_separated_values_options_callback,
450 help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
451
452 downloader = optparse.OptionGroup(parser, 'Download Options')
453 downloader.add_option(
454 '-r', '--limit-rate', '--rate-limit',
455 dest='ratelimit', metavar='RATE',
456 help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
457 downloader.add_option(
458 '-R', '--retries',
459 dest='retries', metavar='RETRIES', default=10,
460 help='Number of retries (default is %default), or "infinite".')
461 downloader.add_option(
462 '--fragment-retries',
463 dest='fragment_retries', metavar='RETRIES', default=10,
464 help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
465 downloader.add_option(
466 '--skip-unavailable-fragments',
467 action='store_true', dest='skip_unavailable_fragments', default=True,
468 help='Skip unavailable fragments (DASH, hlsnative and ISM)')
469 downloader.add_option(
470 '--abort-on-unavailable-fragment',
471 action='store_false', dest='skip_unavailable_fragments',
472 help='Abort downloading when some fragment is not available')
473 downloader.add_option(
474 '--keep-fragments',
475 action='store_true', dest='keep_fragments', default=False,
476 help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default')
477 downloader.add_option(
478 '--buffer-size',
479 dest='buffersize', metavar='SIZE', default='1024',
480 help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
481 downloader.add_option(
482 '--no-resize-buffer',
483 action='store_true', dest='noresizebuffer', default=False,
484 help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
485 downloader.add_option(
486 '--http-chunk-size',
487 dest='http_chunk_size', metavar='SIZE', default=None,
488 help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
489 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)')
490 downloader.add_option(
491 '--test',
492 action='store_true', dest='test', default=False,
493 help=optparse.SUPPRESS_HELP)
494 downloader.add_option(
495 '--playlist-reverse',
496 action='store_true',
497 help='Download playlist videos in reverse order')
498 downloader.add_option(
499 '--playlist-random',
500 action='store_true',
501 help='Download playlist videos in random order')
502 downloader.add_option(
503 '--xattr-set-filesize',
504 dest='xattr_set_filesize', action='store_true',
505 help='Set file xattribute ytdl.filesize with expected file size')
506 downloader.add_option(
507 '--hls-prefer-native',
508 dest='hls_prefer_native', action='store_true', default=None,
509 help='Use the native HLS downloader instead of ffmpeg')
510 downloader.add_option(
511 '--hls-prefer-ffmpeg',
512 dest='hls_prefer_native', action='store_false', default=None,
513 help='Use ffmpeg instead of the native HLS downloader')
514 downloader.add_option(
515 '--hls-use-mpegts',
516 dest='hls_use_mpegts', action='store_true',
517 help='Use the mpegts container for HLS videos, allowing to play the '
518 'video while downloading (some players may not be able to play it)')
519 downloader.add_option(
520 '--external-downloader',
521 dest='external_downloader', metavar='COMMAND',
522 help='Use the specified external downloader. '
523 'Currently supports %s' % ','.join(list_external_downloaders()))
524 downloader.add_option(
525 '--external-downloader-args',
526 dest='external_downloader_args', metavar='ARGS',
527 help='Give these arguments to the external downloader')
528
529 workarounds = optparse.OptionGroup(parser, 'Workarounds')
530 workarounds.add_option(
531 '--encoding',
532 dest='encoding', metavar='ENCODING',
533 help='Force the specified encoding (experimental)')
534 workarounds.add_option(
535 '--no-check-certificate',
536 action='store_true', dest='no_check_certificate', default=False,
537 help='Suppress HTTPS certificate validation')
538 workarounds.add_option(
539 '--prefer-insecure',
540 '--prefer-unsecure', action='store_true', dest='prefer_insecure',
541 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
542 workarounds.add_option(
543 '--user-agent',
544 metavar='UA', dest='user_agent',
545 help='Specify a custom user agent')
546 workarounds.add_option(
547 '--referer',
548 metavar='URL', dest='referer', default=None,
549 help='Specify a custom referer, use if the video access is restricted to one domain',
550 )
551 workarounds.add_option(
552 '--add-header',
553 metavar='FIELD:VALUE', dest='headers', action='append',
554 help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
555 )
556 workarounds.add_option(
557 '--bidi-workaround',
558 dest='bidi_workaround', action='store_true',
559 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
560 workarounds.add_option(
561 '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
562 dest='sleep_interval', type=float,
563 help=(
564 'Number of seconds to sleep before each download when used alone '
565 'or a lower bound of a range for randomized sleep before each download '
566 '(minimum possible number of seconds to sleep) when used along with '
567 '--max-sleep-interval.'))
568 workarounds.add_option(
569 '--max-sleep-interval', metavar='SECONDS',
570 dest='max_sleep_interval', type=float,
571 help=(
572 'Upper bound of a range for randomized sleep before each download '
573 '(maximum possible number of seconds to sleep). Must only be used '
574 'along with --min-sleep-interval.'))
575
576 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
577 verbosity.add_option(
578 '-q', '--quiet',
579 action='store_true', dest='quiet', default=False,
580 help='Activate quiet mode')
581 verbosity.add_option(
582 '--no-warnings',
583 dest='no_warnings', action='store_true', default=False,
584 help='Ignore warnings')
585 verbosity.add_option(
586 '-s', '--simulate',
587 action='store_true', dest='simulate', default=False,
588 help='Do not download the video and do not write anything to disk')
589 verbosity.add_option(
590 '--skip-download',
591 action='store_true', dest='skip_download', default=False,
592 help='Do not download the video')
593 verbosity.add_option(
594 '-g', '--get-url',
595 action='store_true', dest='geturl', default=False,
596 help='Simulate, quiet but print URL')
597 verbosity.add_option(
598 '-e', '--get-title',
599 action='store_true', dest='gettitle', default=False,
600 help='Simulate, quiet but print title')
601 verbosity.add_option(
602 '--get-id',
603 action='store_true', dest='getid', default=False,
604 help='Simulate, quiet but print id')
605 verbosity.add_option(
606 '--get-thumbnail',
607 action='store_true', dest='getthumbnail', default=False,
608 help='Simulate, quiet but print thumbnail URL')
609 verbosity.add_option(
610 '--get-description',
611 action='store_true', dest='getdescription', default=False,
612 help='Simulate, quiet but print video description')
613 verbosity.add_option(
614 '--get-duration',
615 action='store_true', dest='getduration', default=False,
616 help='Simulate, quiet but print video length')
617 verbosity.add_option(
618 '--get-filename',
619 action='store_true', dest='getfilename', default=False,
620 help='Simulate, quiet but print output filename')
621 verbosity.add_option(
622 '--get-format',
623 action='store_true', dest='getformat', default=False,
624 help='Simulate, quiet but print output format')
625 verbosity.add_option(
626 '-j', '--dump-json',
627 action='store_true', dest='dumpjson', default=False,
628 help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.')
629 verbosity.add_option(
630 '-J', '--dump-single-json',
631 action='store_true', dest='dump_single_json', default=False,
632 help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.')
633 verbosity.add_option(
634 '--print-json',
635 action='store_true', dest='print_json', default=False,
636 help='Be quiet and print the video information as JSON (video is still being downloaded).',
637 )
638 verbosity.add_option(
639 '--newline',
640 action='store_true', dest='progress_with_newline', default=False,
641 help='Output progress bar as new lines')
642 verbosity.add_option(
643 '--no-progress',
644 action='store_true', dest='noprogress', default=False,
645 help='Do not print progress bar')
646 verbosity.add_option(
647 '--console-title',
648 action='store_true', dest='consoletitle', default=False,
649 help='Display progress in console titlebar')
650 verbosity.add_option(
651 '-v', '--verbose',
652 action='store_true', dest='verbose', default=False,
653 help='Print various debugging information')
654 verbosity.add_option(
655 '--dump-pages', '--dump-intermediate-pages',
656 action='store_true', dest='dump_intermediate_pages', default=False,
657 help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
658 verbosity.add_option(
659 '--write-pages',
660 action='store_true', dest='write_pages', default=False,
661 help='Write downloaded intermediary pages to files in the current directory to debug problems')
662 verbosity.add_option(
663 '--youtube-print-sig-code',
664 action='store_true', dest='youtube_print_sig_code', default=False,
665 help=optparse.SUPPRESS_HELP)
666 verbosity.add_option(
667 '--print-traffic', '--dump-headers',
668 dest='debug_printtraffic', action='store_true', default=False,
669 help='Display sent and read HTTP traffic')
670 verbosity.add_option(
671 '-C', '--call-home',
672 dest='call_home', action='store_true', default=False,
673 help='Contact the youtube-dl server for debugging')
674 verbosity.add_option(
675 '--no-call-home',
676 dest='call_home', action='store_false', default=False,
677 help='Do NOT contact the youtube-dl server for debugging')
678
679 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
680 filesystem.add_option(
681 '-a', '--batch-file',
682 dest='batchfile', metavar='FILE',
683 help="File containing URLs to download ('-' for stdin), one URL per line. "
684 "Lines starting with '#', ';' or ']' are considered as comments and ignored.")
685 filesystem.add_option(
686 '--id', default=False,
687 action='store_true', dest='useid', help='Use only video ID in file name')
688 filesystem.add_option(
689 '-o', '--output',
690 dest='outtmpl', metavar='TEMPLATE',
691 help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info'))
692 filesystem.add_option(
693 '--autonumber-size',
694 dest='autonumber_size', metavar='NUMBER', type=int,
695 help=optparse.SUPPRESS_HELP)
696 filesystem.add_option(
697 '--autonumber-start',
698 dest='autonumber_start', metavar='NUMBER', default=1, type=int,
699 help='Specify the start value for %(autonumber)s (default is %default)')
700 filesystem.add_option(
701 '--restrict-filenames',
702 action='store_true', dest='restrictfilenames', default=False,
703 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
704 filesystem.add_option(
705 '-A', '--auto-number',
706 action='store_true', dest='autonumber', default=False,
707 help=optparse.SUPPRESS_HELP)
708 filesystem.add_option(
709 '-t', '--title',
710 action='store_true', dest='usetitle', default=False,
711 help=optparse.SUPPRESS_HELP)
712 filesystem.add_option(
713 '-l', '--literal', default=False,
714 action='store_true', dest='usetitle',
715 help=optparse.SUPPRESS_HELP)
716 filesystem.add_option(
717 '-w', '--no-overwrites',
718 action='store_true', dest='nooverwrites', default=False,
719 help='Do not overwrite files')
720 filesystem.add_option(
721 '-c', '--continue',
722 action='store_true', dest='continue_dl', default=True,
723 help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
724 filesystem.add_option(
725 '--no-continue',
726 action='store_false', dest='continue_dl',
727 help='Do not resume partially downloaded files (restart from beginning)')
728 filesystem.add_option(
729 '--no-part',
730 action='store_true', dest='nopart', default=False,
731 help='Do not use .part files - write directly into output file')
732 filesystem.add_option(
733 '--no-mtime',
734 action='store_false', dest='updatetime', default=True,
735 help='Do not use the Last-modified header to set the file modification time')
736 filesystem.add_option(
737 '--write-description',
738 action='store_true', dest='writedescription', default=False,
739 help='Write video description to a .description file')
740 filesystem.add_option(
741 '--write-info-json',
742 action='store_true', dest='writeinfojson', default=False,
743 help='Write video metadata to a .info.json file')
744 filesystem.add_option(
745 '--write-annotations',
746 action='store_true', dest='writeannotations', default=False,
747 help='Write video annotations to a .annotations.xml file')
748 filesystem.add_option(
749 '--load-info-json', '--load-info',
750 dest='load_info_filename', metavar='FILE',
751 help='JSON file containing the video information (created with the "--write-info-json" option)')
752 filesystem.add_option(
753 '--cookies',
754 dest='cookiefile', metavar='FILE',
755 help='File to read cookies from and dump cookie jar in')
756 filesystem.add_option(
757 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
758 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.')
759 filesystem.add_option(
760 '--no-cache-dir', action='store_const', const=False, dest='cachedir',
761 help='Disable filesystem caching')
762 filesystem.add_option(
763 '--rm-cache-dir',
764 action='store_true', dest='rm_cachedir',
765 help='Delete all filesystem cache files')
766
767 thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
768 thumbnail.add_option(
769 '--write-thumbnail',
770 action='store_true', dest='writethumbnail', default=False,
771 help='Write thumbnail image to disk')
772 thumbnail.add_option(
773 '--write-all-thumbnails',
774 action='store_true', dest='write_all_thumbnails', default=False,
775 help='Write all thumbnail image formats to disk')
776 thumbnail.add_option(
777 '--list-thumbnails',
778 action='store_true', dest='list_thumbnails', default=False,
779 help='Simulate and list all available thumbnail formats')
780
781 postproc = optparse.OptionGroup(parser, 'Post-processing Options')
782 postproc.add_option(
783 '-x', '--extract-audio',
784 action='store_true', dest='extractaudio', default=False,
785 help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
786 postproc.add_option(
787 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
788 help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
789 postproc.add_option(
790 '--audio-quality', metavar='QUALITY',
791 dest='audioquality', default='5',
792 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)')
793 postproc.add_option(
794 '--recode-video',
795 metavar='FORMAT', dest='recodevideo', default=None,
796 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
797 postproc.add_option(
798 '--postprocessor-args',
799 dest='postprocessor_args', metavar='ARGS',
800 help='Give these arguments to the postprocessor')
801 postproc.add_option(
802 '-k', '--keep-video',
803 action='store_true', dest='keepvideo', default=False,
804 help='Keep the video file on disk after the post-processing; the video is erased by default')
805 postproc.add_option(
806 '--no-post-overwrites',
807 action='store_true', dest='nopostoverwrites', default=False,
808 help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
809 postproc.add_option(
810 '--embed-subs',
811 action='store_true', dest='embedsubtitles', default=False,
812 help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
813 postproc.add_option(
814 '--embed-thumbnail',
815 action='store_true', dest='embedthumbnail', default=False,
816 help='Embed thumbnail in the audio as cover art')
817 postproc.add_option(
818 '--add-metadata',
819 action='store_true', dest='addmetadata', default=False,
820 help='Write metadata to the video file')
821 postproc.add_option(
822 '--metadata-from-title',
823 metavar='FORMAT', dest='metafromtitle',
824 help='Parse additional metadata like song title / artist from the video title. '
825 'The format syntax is the same as --output. Regular expression with '
826 'named capture groups may also be used. '
827 'The parsed parameters replace existing values. '
828 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
829 '"Coldplay - Paradise". '
830 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"')
831 postproc.add_option(
832 '--xattrs',
833 action='store_true', dest='xattrs', default=False,
834 help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
835 postproc.add_option(
836 '--fixup',
837 metavar='POLICY', dest='fixup', default='detect_or_warn',
838 help='Automatically correct known faults of the file. '
839 'One of never (do nothing), warn (only emit a warning), '
840 'detect_or_warn (the default; fix file if we can, warn otherwise)')
841 postproc.add_option(
842 '--prefer-avconv',
843 action='store_false', dest='prefer_ffmpeg',
844 help='Prefer avconv over ffmpeg for running the postprocessors')
845 postproc.add_option(
846 '--prefer-ffmpeg',
847 action='store_true', dest='prefer_ffmpeg',
848 help='Prefer ffmpeg over avconv for running the postprocessors (default)')
849 postproc.add_option(
850 '--ffmpeg-location', '--avconv-location', metavar='PATH',
851 dest='ffmpeg_location',
852 help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
853 postproc.add_option(
854 '--exec',
855 metavar='CMD', dest='exec_cmd',
856 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 {}\'')
857 postproc.add_option(
858 '--convert-subs', '--convert-subtitles',
859 metavar='FORMAT', dest='convertsubtitles', default=None,
860 help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
861
862 parser.add_option_group(general)
863 parser.add_option_group(network)
864 parser.add_option_group(geo)
865 parser.add_option_group(selection)
866 parser.add_option_group(downloader)
867 parser.add_option_group(filesystem)
868 parser.add_option_group(thumbnail)
869 parser.add_option_group(verbosity)
870 parser.add_option_group(workarounds)
871 parser.add_option_group(video_format)
872 parser.add_option_group(subtitles)
873 parser.add_option_group(authentication)
874 parser.add_option_group(adobe_pass)
875 parser.add_option_group(postproc)
876
877 if overrideArguments is not None:
878 opts, args = parser.parse_args(overrideArguments)
879 if opts.verbose:
880 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
881 else:
882 def compat_conf(conf):
883 if sys.version_info < (3,):
884 return [a.decode(preferredencoding(), 'replace') for a in conf]
885 return conf
886
887 command_line_conf = compat_conf(sys.argv[1:])
888 opts, args = parser.parse_args(command_line_conf)
889
890 system_conf = user_conf = custom_conf = []
891
892 if '--config-location' in command_line_conf:
893 location = compat_expanduser(opts.config_location)
894 if os.path.isdir(location):
895 location = os.path.join(location, 'youtube-dl.conf')
896 if not os.path.exists(location):
897 parser.error('config-location %s does not exist.' % location)
898 custom_conf = _readOptions(location)
899 elif '--ignore-config' in command_line_conf:
900 pass
901 else:
902 system_conf = _readOptions('/etc/youtube-dl.conf')
903 if '--ignore-config' not in system_conf:
904 user_conf = _readUserConf()
905
906 argv = system_conf + user_conf + custom_conf + command_line_conf
907 opts, args = parser.parse_args(argv)
908 if opts.verbose:
909 for conf_label, conf in (
910 ('System config', system_conf),
911 ('User config', user_conf),
912 ('Custom config', custom_conf),
913 ('Command-line args', command_line_conf)):
914 write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
915
916 return parser, opts, args