]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/options.py
Adapt changes from Andreas Tille for porting to Salsa.
[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/rg3/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 '-v', '--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 experimental '
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 options 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 (experimental)')
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 (experimental)')
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 (experimental)')
252
253 selection = optparse.OptionGroup(parser, 'Video Selection')
254 selection.add_option(
255 '--playlist-start',
256 dest='playliststart', metavar='NUMBER', default=1, type=int,
257 help='Playlist video to start at (default is %default)')
258 selection.add_option(
259 '--playlist-end',
260 dest='playlistend', metavar='NUMBER', default=None, type=int,
261 help='Playlist video to end at (default is last)')
262 selection.add_option(
263 '--playlist-items',
264 dest='playlist_items', metavar='ITEM_SPEC', default=None,
265 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.')
266 selection.add_option(
267 '--match-title',
268 dest='matchtitle', metavar='REGEX',
269 help='Download only matching titles (regex or caseless sub-string)')
270 selection.add_option(
271 '--reject-title',
272 dest='rejecttitle', metavar='REGEX',
273 help='Skip download for matching titles (regex or caseless sub-string)')
274 selection.add_option(
275 '--max-downloads',
276 dest='max_downloads', metavar='NUMBER', type=int, default=None,
277 help='Abort after downloading NUMBER files')
278 selection.add_option(
279 '--min-filesize',
280 metavar='SIZE', dest='min_filesize', default=None,
281 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
282 selection.add_option(
283 '--max-filesize',
284 metavar='SIZE', dest='max_filesize', default=None,
285 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
286 selection.add_option(
287 '--date',
288 metavar='DATE', dest='date', default=None,
289 help='Download only videos uploaded in this date')
290 selection.add_option(
291 '--datebefore',
292 metavar='DATE', dest='datebefore', default=None,
293 help='Download only videos uploaded on or before this date (i.e. inclusive)')
294 selection.add_option(
295 '--dateafter',
296 metavar='DATE', dest='dateafter', default=None,
297 help='Download only videos uploaded on or after this date (i.e. inclusive)')
298 selection.add_option(
299 '--min-views',
300 metavar='COUNT', dest='min_views', default=None, type=int,
301 help='Do not download any videos with less than COUNT views')
302 selection.add_option(
303 '--max-views',
304 metavar='COUNT', dest='max_views', default=None, type=int,
305 help='Do not download any videos with more than COUNT views')
306 selection.add_option(
307 '--match-filter',
308 metavar='FILTER', dest='match_filter', default=None,
309 help=(
310 'Generic video filter. '
311 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to '
312 'match if the key is present, '
313 '!key to check if the key is not present, '
314 'key > NUMBER (like "comment_count > 12", also works with '
315 '>=, <, <=, !=, =) to compare against a number, '
316 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
317 'to match against a string literal '
318 'and & to require multiple matches. '
319 'Values which are not known are excluded unless you '
320 'put a question mark (?) after the operator. '
321 'For example, to only match videos that have been liked more than '
322 '100 times and disliked less than 50 times (or the dislike '
323 'functionality is not available at the given service), but who '
324 'also have a description, use --match-filter '
325 '"like_count > 100 & dislike_count <? 50 & description" .'
326 ))
327 selection.add_option(
328 '--no-playlist',
329 action='store_true', dest='noplaylist', default=False,
330 help='Download only the video, if the URL refers to a video and a playlist.')
331 selection.add_option(
332 '--yes-playlist',
333 action='store_false', dest='noplaylist', default=False,
334 help='Download the playlist, if the URL refers to a video and a playlist.')
335 selection.add_option(
336 '--age-limit',
337 metavar='YEARS', dest='age_limit', default=None, type=int,
338 help='Download only videos suitable for the given age')
339 selection.add_option(
340 '--download-archive', metavar='FILE',
341 dest='download_archive',
342 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
343 selection.add_option(
344 '--include-ads',
345 dest='include_ads', action='store_true',
346 help='Download advertisements as well (experimental)')
347
348 authentication = optparse.OptionGroup(parser, 'Authentication Options')
349 authentication.add_option(
350 '-u', '--username',
351 dest='username', metavar='USERNAME',
352 help='Login with this account ID')
353 authentication.add_option(
354 '-p', '--password',
355 dest='password', metavar='PASSWORD',
356 help='Account password. If this option is left out, youtube-dl will ask interactively.')
357 authentication.add_option(
358 '-2', '--twofactor',
359 dest='twofactor', metavar='TWOFACTOR',
360 help='Two-factor authentication code')
361 authentication.add_option(
362 '-n', '--netrc',
363 action='store_true', dest='usenetrc', default=False,
364 help='Use .netrc authentication data')
365 authentication.add_option(
366 '--video-password',
367 dest='videopassword', metavar='PASSWORD',
368 help='Video password (vimeo, smotri, youku)')
369
370 adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
371 adobe_pass.add_option(
372 '--ap-mso',
373 dest='ap_mso', metavar='MSO',
374 help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
375 adobe_pass.add_option(
376 '--ap-username',
377 dest='ap_username', metavar='USERNAME',
378 help='Multiple-system operator account login')
379 adobe_pass.add_option(
380 '--ap-password',
381 dest='ap_password', metavar='PASSWORD',
382 help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.')
383 adobe_pass.add_option(
384 '--ap-list-mso',
385 action='store_true', dest='ap_list_mso', default=False,
386 help='List all supported multiple-system operators')
387
388 video_format = optparse.OptionGroup(parser, 'Video Format Options')
389 video_format.add_option(
390 '-f', '--format',
391 action='store', dest='format', metavar='FORMAT', default=None,
392 help='Video format code, see the "FORMAT SELECTION" for all the info')
393 video_format.add_option(
394 '--all-formats',
395 action='store_const', dest='format', const='all',
396 help='Download all available video formats')
397 video_format.add_option(
398 '--prefer-free-formats',
399 action='store_true', dest='prefer_free_formats', default=False,
400 help='Prefer free video formats unless a specific one is requested')
401 video_format.add_option(
402 '-F', '--list-formats',
403 action='store_true', dest='listformats',
404 help='List all available formats of requested videos')
405 video_format.add_option(
406 '--youtube-include-dash-manifest',
407 action='store_true', dest='youtube_include_dash_manifest', default=True,
408 help=optparse.SUPPRESS_HELP)
409 video_format.add_option(
410 '--youtube-skip-dash-manifest',
411 action='store_false', dest='youtube_include_dash_manifest',
412 help='Do not download the DASH manifests and related data on YouTube videos')
413 video_format.add_option(
414 '--merge-output-format',
415 action='store', dest='merge_output_format', metavar='FORMAT', default=None,
416 help=(
417 'If a merge is required (e.g. bestvideo+bestaudio), '
418 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
419 'Ignored if no merge is required'))
420
421 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
422 subtitles.add_option(
423 '--write-sub', '--write-srt',
424 action='store_true', dest='writesubtitles', default=False,
425 help='Write subtitle file')
426 subtitles.add_option(
427 '--write-auto-sub', '--write-automatic-sub',
428 action='store_true', dest='writeautomaticsub', default=False,
429 help='Write automatically generated subtitle file (YouTube only)')
430 subtitles.add_option(
431 '--all-subs',
432 action='store_true', dest='allsubtitles', default=False,
433 help='Download all the available subtitles of the video')
434 subtitles.add_option(
435 '--list-subs',
436 action='store_true', dest='listsubtitles', default=False,
437 help='List all available subtitles for the video')
438 subtitles.add_option(
439 '--sub-format',
440 action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
441 help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
442 subtitles.add_option(
443 '--sub-lang', '--sub-langs', '--srt-lang',
444 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
445 default=[], callback=_comma_separated_values_options_callback,
446 help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
447
448 downloader = optparse.OptionGroup(parser, 'Download Options')
449 downloader.add_option(
450 '-r', '--limit-rate', '--rate-limit',
451 dest='ratelimit', metavar='RATE',
452 help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
453 downloader.add_option(
454 '-R', '--retries',
455 dest='retries', metavar='RETRIES', default=10,
456 help='Number of retries (default is %default), or "infinite".')
457 downloader.add_option(
458 '--fragment-retries',
459 dest='fragment_retries', metavar='RETRIES', default=10,
460 help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
461 downloader.add_option(
462 '--skip-unavailable-fragments',
463 action='store_true', dest='skip_unavailable_fragments', default=True,
464 help='Skip unavailable fragments (DASH, hlsnative and ISM)')
465 downloader.add_option(
466 '--abort-on-unavailable-fragment',
467 action='store_false', dest='skip_unavailable_fragments',
468 help='Abort downloading when some fragment is not available')
469 downloader.add_option(
470 '--keep-fragments',
471 action='store_true', dest='keep_fragments', default=False,
472 help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default')
473 downloader.add_option(
474 '--buffer-size',
475 dest='buffersize', metavar='SIZE', default='1024',
476 help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
477 downloader.add_option(
478 '--no-resize-buffer',
479 action='store_true', dest='noresizebuffer', default=False,
480 help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
481 downloader.add_option(
482 '--test',
483 action='store_true', dest='test', default=False,
484 help=optparse.SUPPRESS_HELP)
485 downloader.add_option(
486 '--playlist-reverse',
487 action='store_true',
488 help='Download playlist videos in reverse order')
489 downloader.add_option(
490 '--playlist-random',
491 action='store_true',
492 help='Download playlist videos in random order')
493 downloader.add_option(
494 '--xattr-set-filesize',
495 dest='xattr_set_filesize', action='store_true',
496 help='Set file xattribute ytdl.filesize with expected file size (experimental)')
497 downloader.add_option(
498 '--hls-prefer-native',
499 dest='hls_prefer_native', action='store_true', default=None,
500 help='Use the native HLS downloader instead of ffmpeg')
501 downloader.add_option(
502 '--hls-prefer-ffmpeg',
503 dest='hls_prefer_native', action='store_false', default=None,
504 help='Use ffmpeg instead of the native HLS downloader')
505 downloader.add_option(
506 '--hls-use-mpegts',
507 dest='hls_use_mpegts', action='store_true',
508 help='Use the mpegts container for HLS videos, allowing to play the '
509 'video while downloading (some players may not be able to play it)')
510 downloader.add_option(
511 '--external-downloader',
512 dest='external_downloader', metavar='COMMAND',
513 help='Use the specified external downloader. '
514 'Currently supports %s' % ','.join(list_external_downloaders()))
515 downloader.add_option(
516 '--external-downloader-args',
517 dest='external_downloader_args', metavar='ARGS',
518 help='Give these arguments to the external downloader')
519
520 workarounds = optparse.OptionGroup(parser, 'Workarounds')
521 workarounds.add_option(
522 '--encoding',
523 dest='encoding', metavar='ENCODING',
524 help='Force the specified encoding (experimental)')
525 workarounds.add_option(
526 '--no-check-certificate',
527 action='store_true', dest='no_check_certificate', default=False,
528 help='Suppress HTTPS certificate validation')
529 workarounds.add_option(
530 '--prefer-insecure',
531 '--prefer-unsecure', action='store_true', dest='prefer_insecure',
532 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
533 workarounds.add_option(
534 '--user-agent',
535 metavar='UA', dest='user_agent',
536 help='Specify a custom user agent')
537 workarounds.add_option(
538 '--referer',
539 metavar='URL', dest='referer', default=None,
540 help='Specify a custom referer, use if the video access is restricted to one domain',
541 )
542 workarounds.add_option(
543 '--add-header',
544 metavar='FIELD:VALUE', dest='headers', action='append',
545 help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
546 )
547 workarounds.add_option(
548 '--bidi-workaround',
549 dest='bidi_workaround', action='store_true',
550 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
551 workarounds.add_option(
552 '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
553 dest='sleep_interval', type=float,
554 help=(
555 'Number of seconds to sleep before each download when used alone '
556 'or a lower bound of a range for randomized sleep before each download '
557 '(minimum possible number of seconds to sleep) when used along with '
558 '--max-sleep-interval.'))
559 workarounds.add_option(
560 '--max-sleep-interval', metavar='SECONDS',
561 dest='max_sleep_interval', type=float,
562 help=(
563 'Upper bound of a range for randomized sleep before each download '
564 '(maximum possible number of seconds to sleep). Must only be used '
565 'along with --min-sleep-interval.'))
566
567 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
568 verbosity.add_option(
569 '-q', '--quiet',
570 action='store_true', dest='quiet', default=False,
571 help='Activate quiet mode')
572 verbosity.add_option(
573 '--no-warnings',
574 dest='no_warnings', action='store_true', default=False,
575 help='Ignore warnings')
576 verbosity.add_option(
577 '-s', '--simulate',
578 action='store_true', dest='simulate', default=False,
579 help='Do not download the video and do not write anything to disk')
580 verbosity.add_option(
581 '--skip-download',
582 action='store_true', dest='skip_download', default=False,
583 help='Do not download the video')
584 verbosity.add_option(
585 '-g', '--get-url',
586 action='store_true', dest='geturl', default=False,
587 help='Simulate, quiet but print URL')
588 verbosity.add_option(
589 '-e', '--get-title',
590 action='store_true', dest='gettitle', default=False,
591 help='Simulate, quiet but print title')
592 verbosity.add_option(
593 '--get-id',
594 action='store_true', dest='getid', default=False,
595 help='Simulate, quiet but print id')
596 verbosity.add_option(
597 '--get-thumbnail',
598 action='store_true', dest='getthumbnail', default=False,
599 help='Simulate, quiet but print thumbnail URL')
600 verbosity.add_option(
601 '--get-description',
602 action='store_true', dest='getdescription', default=False,
603 help='Simulate, quiet but print video description')
604 verbosity.add_option(
605 '--get-duration',
606 action='store_true', dest='getduration', default=False,
607 help='Simulate, quiet but print video length')
608 verbosity.add_option(
609 '--get-filename',
610 action='store_true', dest='getfilename', default=False,
611 help='Simulate, quiet but print output filename')
612 verbosity.add_option(
613 '--get-format',
614 action='store_true', dest='getformat', default=False,
615 help='Simulate, quiet but print output format')
616 verbosity.add_option(
617 '-j', '--dump-json',
618 action='store_true', dest='dumpjson', default=False,
619 help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.')
620 verbosity.add_option(
621 '-J', '--dump-single-json',
622 action='store_true', dest='dump_single_json', default=False,
623 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.')
624 verbosity.add_option(
625 '--print-json',
626 action='store_true', dest='print_json', default=False,
627 help='Be quiet and print the video information as JSON (video is still being downloaded).',
628 )
629 verbosity.add_option(
630 '--newline',
631 action='store_true', dest='progress_with_newline', default=False,
632 help='Output progress bar as new lines')
633 verbosity.add_option(
634 '--no-progress',
635 action='store_true', dest='noprogress', default=False,
636 help='Do not print progress bar')
637 verbosity.add_option(
638 '--console-title',
639 action='store_true', dest='consoletitle', default=False,
640 help='Display progress in console titlebar')
641 verbosity.add_option(
642 '-v', '--verbose',
643 action='store_true', dest='verbose', default=False,
644 help='Print various debugging information')
645 verbosity.add_option(
646 '--dump-pages', '--dump-intermediate-pages',
647 action='store_true', dest='dump_intermediate_pages', default=False,
648 help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
649 verbosity.add_option(
650 '--write-pages',
651 action='store_true', dest='write_pages', default=False,
652 help='Write downloaded intermediary pages to files in the current directory to debug problems')
653 verbosity.add_option(
654 '--youtube-print-sig-code',
655 action='store_true', dest='youtube_print_sig_code', default=False,
656 help=optparse.SUPPRESS_HELP)
657 verbosity.add_option(
658 '--print-traffic', '--dump-headers',
659 dest='debug_printtraffic', action='store_true', default=False,
660 help='Display sent and read HTTP traffic')
661 verbosity.add_option(
662 '-C', '--call-home',
663 dest='call_home', action='store_true', default=False,
664 help='Contact the youtube-dl server for debugging')
665 verbosity.add_option(
666 '--no-call-home',
667 dest='call_home', action='store_false', default=False,
668 help='Do NOT contact the youtube-dl server for debugging')
669
670 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
671 filesystem.add_option(
672 '-a', '--batch-file',
673 dest='batchfile', metavar='FILE',
674 help='File containing URLs to download (\'-\' for stdin)')
675 filesystem.add_option(
676 '--id', default=False,
677 action='store_true', dest='useid', help='Use only video ID in file name')
678 filesystem.add_option(
679 '-o', '--output',
680 dest='outtmpl', metavar='TEMPLATE',
681 help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info'))
682 filesystem.add_option(
683 '--autonumber-size',
684 dest='autonumber_size', metavar='NUMBER', type=int,
685 help=optparse.SUPPRESS_HELP)
686 filesystem.add_option(
687 '--autonumber-start',
688 dest='autonumber_start', metavar='NUMBER', default=1, type=int,
689 help='Specify the start value for %(autonumber)s (default is %default)')
690 filesystem.add_option(
691 '--restrict-filenames',
692 action='store_true', dest='restrictfilenames', default=False,
693 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
694 filesystem.add_option(
695 '-A', '--auto-number',
696 action='store_true', dest='autonumber', default=False,
697 help=optparse.SUPPRESS_HELP)
698 filesystem.add_option(
699 '-t', '--title',
700 action='store_true', dest='usetitle', default=False,
701 help=optparse.SUPPRESS_HELP)
702 filesystem.add_option(
703 '-l', '--literal', default=False,
704 action='store_true', dest='usetitle',
705 help=optparse.SUPPRESS_HELP)
706 filesystem.add_option(
707 '-w', '--no-overwrites',
708 action='store_true', dest='nooverwrites', default=False,
709 help='Do not overwrite files')
710 filesystem.add_option(
711 '-c', '--continue',
712 action='store_true', dest='continue_dl', default=True,
713 help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
714 filesystem.add_option(
715 '--no-continue',
716 action='store_false', dest='continue_dl',
717 help='Do not resume partially downloaded files (restart from beginning)')
718 filesystem.add_option(
719 '--no-part',
720 action='store_true', dest='nopart', default=False,
721 help='Do not use .part files - write directly into output file')
722 filesystem.add_option(
723 '--no-mtime',
724 action='store_false', dest='updatetime', default=True,
725 help='Do not use the Last-modified header to set the file modification time')
726 filesystem.add_option(
727 '--write-description',
728 action='store_true', dest='writedescription', default=False,
729 help='Write video description to a .description file')
730 filesystem.add_option(
731 '--write-info-json',
732 action='store_true', dest='writeinfojson', default=False,
733 help='Write video metadata to a .info.json file')
734 filesystem.add_option(
735 '--write-annotations',
736 action='store_true', dest='writeannotations', default=False,
737 help='Write video annotations to a .annotations.xml file')
738 filesystem.add_option(
739 '--load-info-json', '--load-info',
740 dest='load_info_filename', metavar='FILE',
741 help='JSON file containing the video information (created with the "--write-info-json" option)')
742 filesystem.add_option(
743 '--cookies',
744 dest='cookiefile', metavar='FILE',
745 help='File to read cookies from and dump cookie jar in')
746 filesystem.add_option(
747 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
748 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.')
749 filesystem.add_option(
750 '--no-cache-dir', action='store_const', const=False, dest='cachedir',
751 help='Disable filesystem caching')
752 filesystem.add_option(
753 '--rm-cache-dir',
754 action='store_true', dest='rm_cachedir',
755 help='Delete all filesystem cache files')
756
757 thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
758 thumbnail.add_option(
759 '--write-thumbnail',
760 action='store_true', dest='writethumbnail', default=False,
761 help='Write thumbnail image to disk')
762 thumbnail.add_option(
763 '--write-all-thumbnails',
764 action='store_true', dest='write_all_thumbnails', default=False,
765 help='Write all thumbnail image formats to disk')
766 thumbnail.add_option(
767 '--list-thumbnails',
768 action='store_true', dest='list_thumbnails', default=False,
769 help='Simulate and list all available thumbnail formats')
770
771 postproc = optparse.OptionGroup(parser, 'Post-processing Options')
772 postproc.add_option(
773 '-x', '--extract-audio',
774 action='store_true', dest='extractaudio', default=False,
775 help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
776 postproc.add_option(
777 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
778 help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
779 postproc.add_option(
780 '--audio-quality', metavar='QUALITY',
781 dest='audioquality', default='5',
782 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)')
783 postproc.add_option(
784 '--recode-video',
785 metavar='FORMAT', dest='recodevideo', default=None,
786 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
787 postproc.add_option(
788 '--postprocessor-args',
789 dest='postprocessor_args', metavar='ARGS',
790 help='Give these arguments to the postprocessor')
791 postproc.add_option(
792 '-k', '--keep-video',
793 action='store_true', dest='keepvideo', default=False,
794 help='Keep the video file on disk after the post-processing; the video is erased by default')
795 postproc.add_option(
796 '--no-post-overwrites',
797 action='store_true', dest='nopostoverwrites', default=False,
798 help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
799 postproc.add_option(
800 '--embed-subs',
801 action='store_true', dest='embedsubtitles', default=False,
802 help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
803 postproc.add_option(
804 '--embed-thumbnail',
805 action='store_true', dest='embedthumbnail', default=False,
806 help='Embed thumbnail in the audio as cover art')
807 postproc.add_option(
808 '--add-metadata',
809 action='store_true', dest='addmetadata', default=False,
810 help='Write metadata to the video file')
811 postproc.add_option(
812 '--metadata-from-title',
813 metavar='FORMAT', dest='metafromtitle',
814 help='Parse additional metadata like song title / artist from the video title. '
815 'The format syntax is the same as --output. Regular expression with '
816 'named capture groups may also be used. '
817 'The parsed parameters replace existing values. '
818 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
819 '"Coldplay - Paradise". '
820 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"')
821 postproc.add_option(
822 '--xattrs',
823 action='store_true', dest='xattrs', default=False,
824 help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
825 postproc.add_option(
826 '--fixup',
827 metavar='POLICY', dest='fixup', default='detect_or_warn',
828 help='Automatically correct known faults of the file. '
829 'One of never (do nothing), warn (only emit a warning), '
830 'detect_or_warn (the default; fix file if we can, warn otherwise)')
831 postproc.add_option(
832 '--prefer-avconv',
833 action='store_false', dest='prefer_ffmpeg',
834 help='Prefer avconv over ffmpeg for running the postprocessors (default)')
835 postproc.add_option(
836 '--prefer-ffmpeg',
837 action='store_true', dest='prefer_ffmpeg',
838 help='Prefer ffmpeg over avconv for running the postprocessors')
839 postproc.add_option(
840 '--ffmpeg-location', '--avconv-location', metavar='PATH',
841 dest='ffmpeg_location',
842 help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
843 postproc.add_option(
844 '--exec',
845 metavar='CMD', dest='exec_cmd',
846 help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
847 postproc.add_option(
848 '--convert-subs', '--convert-subtitles',
849 metavar='FORMAT', dest='convertsubtitles', default=None,
850 help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
851
852 parser.add_option_group(general)
853 parser.add_option_group(network)
854 parser.add_option_group(geo)
855 parser.add_option_group(selection)
856 parser.add_option_group(downloader)
857 parser.add_option_group(filesystem)
858 parser.add_option_group(thumbnail)
859 parser.add_option_group(verbosity)
860 parser.add_option_group(workarounds)
861 parser.add_option_group(video_format)
862 parser.add_option_group(subtitles)
863 parser.add_option_group(authentication)
864 parser.add_option_group(adobe_pass)
865 parser.add_option_group(postproc)
866
867 if overrideArguments is not None:
868 opts, args = parser.parse_args(overrideArguments)
869 if opts.verbose:
870 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
871 else:
872 def compat_conf(conf):
873 if sys.version_info < (3,):
874 return [a.decode(preferredencoding(), 'replace') for a in conf]
875 return conf
876
877 command_line_conf = compat_conf(sys.argv[1:])
878 opts, args = parser.parse_args(command_line_conf)
879
880 system_conf = user_conf = custom_conf = []
881
882 if '--config-location' in command_line_conf:
883 location = compat_expanduser(opts.config_location)
884 if os.path.isdir(location):
885 location = os.path.join(location, 'youtube-dl.conf')
886 if not os.path.exists(location):
887 parser.error('config-location %s does not exist.' % location)
888 custom_conf = _readOptions(location)
889 elif '--ignore-config' in command_line_conf:
890 pass
891 else:
892 system_conf = _readOptions('/etc/youtube-dl.conf')
893 if '--ignore-config' not in system_conf:
894 user_conf = _readUserConf()
895
896 argv = system_conf + user_conf + custom_conf + command_line_conf
897 opts, args = parser.parse_args(argv)
898 if opts.verbose:
899 for conf_label, conf in (
900 ('System config', system_conf),
901 ('User config', user_conf),
902 ('Custom config', custom_conf),
903 ('Command-line args', command_line_conf)):
904 write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
905
906 return parser, opts, args