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