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