1 from __future__ import unicode_literals
17 from .version import __version__
20 def parseOpts(overrideArguments=None):
21 def _readOptions(filename_bytes, default=[]):
23 optionf = open(filename_bytes)
25 return default # silently skip if file is not present
29 res += shlex.split(l, comments=True)
35 xdg_config_home = compat_getenv('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')
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)
47 appdata_dir = compat_getenv('appdata')
49 userConf = _readOptions(
50 os.path.join(appdata_dir, 'youtube-dl', 'config'),
53 userConf = _readOptions(
54 os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
58 userConf = _readOptions(
59 os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),
62 userConf = _readOptions(
63 os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),
71 def _format_option_string(option):
72 ''' ('-o', '--option') -> -o, --format METAVAR'''
76 if option._short_opts:
77 opts.append(option._short_opts[0])
79 opts.append(option._long_opts[0])
83 if option.takes_value():
84 opts.append(' %s' % option.metavar)
88 def _comma_separated_values_options_callback(option, opt_str, value, parser):
89 setattr(parser.values, option.dest, value.split(','))
91 def _hide_login_info(opts):
93 for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
95 i = opts.index(private_opt)
96 opts[i + 1] = 'PRIVATE'
101 # No need to wrap help messages if we're on a wide console
102 columns = get_term_width()
103 max_width = columns if columns else 80
104 max_help_position = 80
106 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
107 fmt.format_option_strings = _format_option_string
110 'version': __version__,
112 'usage': '%prog [OPTIONS] URL [URL...]',
113 'conflict_handler': 'resolve',
116 parser = optparse.OptionParser(**compat_kwargs(kw))
118 general = optparse.OptionGroup(parser, 'General Options')
122 help='print this help text and exit')
126 help='print program version and exit')
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)')
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')
137 action='store_false', dest='ignoreerrors',
138 help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
141 action='store_true', dest='dump_user_agent', default=False,
142 help='display the current browser identification')
145 action='store_true', dest='list_extractors', default=False,
146 help='List all supported extractors and the URLs they would handle')
148 '--extractor-descriptions',
149 action='store_true', dest='list_extractor_descriptions', default=False,
150 help='Output descriptions of all supported extractors')
153 dest='default_search', metavar='PREFIX',
154 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.')
158 help='Do not read configuration files. '
159 'When given in the global configuration file /etc/youtube-dl.conf: '
160 'Do not read the user configuration in ~/.config/youtube-dl/config '
161 '(%APPDATA%/youtube-dl/config.txt on Windows)')
164 action='store_const', dest='extract_flat', const='in_playlist',
166 help='Do not extract the videos of a playlist, only list them.')
168 network = optparse.OptionGroup(parser, 'Network Options')
170 '--proxy', dest='proxy',
171 default=None, metavar='URL',
172 help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
175 dest='socket_timeout', type=float, default=None, metavar='SECONDS',
176 help='Time to wait before giving up, in seconds')
179 metavar='IP', dest='source_address', default=None,
180 help='Client-side IP address to bind to (experimental)',
183 selection = optparse.OptionGroup(parser, 'Video Selection')
184 selection.add_option(
186 dest='playliststart', metavar='NUMBER', default=1, type=int,
187 help='playlist video to start at (default is %default)')
188 selection.add_option(
190 dest='playlistend', metavar='NUMBER', default=None, type=int,
191 help='playlist video to end at (default is last)')
192 selection.add_option(
194 dest='matchtitle', metavar='REGEX',
195 help='download only matching titles (regex or caseless sub-string)')
196 selection.add_option(
198 dest='rejecttitle', metavar='REGEX',
199 help='skip download for matching titles (regex or caseless sub-string)')
200 selection.add_option(
202 dest='max_downloads', metavar='NUMBER', type=int, default=None,
203 help='Abort after downloading NUMBER files')
204 selection.add_option(
206 metavar='SIZE', dest='min_filesize', default=None,
207 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
208 selection.add_option(
210 metavar='SIZE', dest='max_filesize', default=None,
211 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
212 selection.add_option(
214 metavar='DATE', dest='date', default=None,
215 help='download only videos uploaded in this date')
216 selection.add_option(
218 metavar='DATE', dest='datebefore', default=None,
219 help='download only videos uploaded on or before this date (i.e. inclusive)')
220 selection.add_option(
222 metavar='DATE', dest='dateafter', default=None,
223 help='download only videos uploaded on or after this date (i.e. inclusive)')
224 selection.add_option(
226 metavar='COUNT', dest='min_views', default=None, type=int,
227 help='Do not download any videos with less than COUNT views',)
228 selection.add_option(
230 metavar='COUNT', dest='max_views', default=None, type=int,
231 help='Do not download any videos with more than COUNT views')
232 selection.add_option(
234 action='store_true', dest='noplaylist', default=False,
235 help='If the URL refers to a video and a playlist, download only the video.')
236 selection.add_option(
238 metavar='YEARS', dest='age_limit', default=None, type=int,
239 help='download only videos suitable for the given age')
240 selection.add_option(
241 '--download-archive', metavar='FILE',
242 dest='download_archive',
243 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
244 selection.add_option(
246 dest='include_ads', action='store_true',
247 help='Download advertisements as well (experimental)')
249 authentication = optparse.OptionGroup(parser, 'Authentication Options')
250 authentication.add_option(
252 dest='username', metavar='USERNAME',
253 help='login with this account ID')
254 authentication.add_option(
256 dest='password', metavar='PASSWORD',
257 help='account password')
258 authentication.add_option(
260 dest='twofactor', metavar='TWOFACTOR',
261 help='two-factor auth code')
262 authentication.add_option(
264 action='store_true', dest='usenetrc', default=False,
265 help='use .netrc authentication data')
266 authentication.add_option(
268 dest='videopassword', metavar='PASSWORD',
269 help='video password (vimeo, smotri)')
271 video_format = optparse.OptionGroup(parser, 'Video Format Options')
272 video_format.add_option(
274 action='store', dest='format', metavar='FORMAT', default=None,
276 'video format code, specify the order of preference using'
277 ' slashes, as in -f 22/17/18 . '
278 ' Instead of format codes, you can select by extension for the '
279 'extensions aac, m4a, mp3, mp4, ogg, wav, webm. '
280 'You can also use the special names "best",'
281 ' "bestvideo", "bestaudio", "worst". '
282 ' By default, youtube-dl will pick the best quality.'
283 ' Use commas to download multiple audio formats, such as'
284 ' -f 136/137/mp4/bestvideo,140/m4a/bestaudio.'
285 ' You can merge the video and audio of two formats into a single'
286 ' file using -f <video-format>+<audio-format> (requires ffmpeg or'
287 ' avconv), for example -f bestvideo+bestaudio.'))
288 video_format.add_option(
290 action='store_const', dest='format', const='all',
291 help='download all available video formats')
292 video_format.add_option(
293 '--prefer-free-formats',
294 action='store_true', dest='prefer_free_formats', default=False,
295 help='prefer free video formats unless a specific one is requested')
296 video_format.add_option(
298 action='store', dest='format_limit', metavar='FORMAT',
299 help='highest quality format to download')
300 video_format.add_option(
301 '-F', '--list-formats',
302 action='store_true', dest='listformats',
303 help='list all available formats')
304 video_format.add_option(
305 '--youtube-include-dash-manifest',
306 action='store_true', dest='youtube_include_dash_manifest', default=True,
307 help=optparse.SUPPRESS_HELP)
308 video_format.add_option(
309 '--youtube-skip-dash-manifest',
310 action='store_false', dest='youtube_include_dash_manifest',
311 help='Do not download the DASH manifest on YouTube videos')
312 video_format.add_option(
313 '--merge-output-format',
314 action='store', dest='merge_output_format', metavar='FORMAT', default=None,
316 'If a merge is required (e.g. bestvideo+bestaudio), output to given container format. One of mkv, mp4, ogg, webm, flv.'
317 'Ignored if no merge is required'))
319 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
320 subtitles.add_option(
321 '--write-sub', '--write-srt',
322 action='store_true', dest='writesubtitles', default=False,
323 help='write subtitle file')
324 subtitles.add_option(
325 '--write-auto-sub', '--write-automatic-sub',
326 action='store_true', dest='writeautomaticsub', default=False,
327 help='write automatic subtitle file (youtube only)')
328 subtitles.add_option(
330 action='store_true', dest='allsubtitles', default=False,
331 help='downloads all the available subtitles of the video')
332 subtitles.add_option(
334 action='store_true', dest='listsubtitles', default=False,
335 help='lists all available subtitles for the video')
336 subtitles.add_option(
338 action='store', dest='subtitlesformat', metavar='FORMAT', default='srt',
339 help='subtitle format (default=srt) ([sbv/vtt] youtube only)')
340 subtitles.add_option(
341 '--sub-lang', '--sub-langs', '--srt-lang',
342 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
343 default=[], callback=_comma_separated_values_options_callback,
344 help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
346 downloader = optparse.OptionGroup(parser, 'Download Options')
347 downloader.add_option(
348 '-r', '--rate-limit',
349 dest='ratelimit', metavar='LIMIT',
350 help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
351 downloader.add_option(
353 dest='retries', metavar='RETRIES', default=10,
354 help='number of retries (default is %default)')
355 downloader.add_option(
357 dest='buffersize', metavar='SIZE', default='1024',
358 help='size of download buffer (e.g. 1024 or 16K) (default is %default)')
359 downloader.add_option(
360 '--no-resize-buffer',
361 action='store_true', dest='noresizebuffer', default=False,
362 help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
363 downloader.add_option(
365 action='store_true', dest='test', default=False,
366 help=optparse.SUPPRESS_HELP)
367 downloader.add_option(
368 '--playlist-reverse',
370 help='Download playlist videos in reverse order')
372 workarounds = optparse.OptionGroup(parser, 'Workarounds')
373 workarounds.add_option(
375 dest='encoding', metavar='ENCODING',
376 help='Force the specified encoding (experimental)')
377 workarounds.add_option(
378 '--no-check-certificate',
379 action='store_true', dest='no_check_certificate', default=False,
380 help='Suppress HTTPS certificate validation.')
381 workarounds.add_option(
383 '--prefer-unsecure', action='store_true', dest='prefer_insecure',
384 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
385 workarounds.add_option(
387 metavar='UA', dest='user_agent',
388 help='specify a custom user agent')
389 workarounds.add_option(
391 metavar='URL', dest='referer', default=None,
392 help='specify a custom referer, use if the video access is restricted to one domain',
394 workarounds.add_option(
396 metavar='FIELD:VALUE', dest='headers', action='append',
397 help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
399 workarounds.add_option(
401 dest='bidi_workaround', action='store_true',
402 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
404 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
405 verbosity.add_option(
407 action='store_true', dest='quiet', default=False,
408 help='activates quiet mode')
409 verbosity.add_option(
411 dest='no_warnings', action='store_true', default=False,
412 help='Ignore warnings')
413 verbosity.add_option(
415 action='store_true', dest='simulate', default=False,
416 help='do not download the video and do not write anything to disk',)
417 verbosity.add_option(
419 action='store_true', dest='skip_download', default=False,
420 help='do not download the video',)
421 verbosity.add_option(
423 action='store_true', dest='geturl', default=False,
424 help='simulate, quiet but print URL')
425 verbosity.add_option(
427 action='store_true', dest='gettitle', default=False,
428 help='simulate, quiet but print title')
429 verbosity.add_option(
431 action='store_true', dest='getid', default=False,
432 help='simulate, quiet but print id')
433 verbosity.add_option(
435 action='store_true', dest='getthumbnail', default=False,
436 help='simulate, quiet but print thumbnail URL')
437 verbosity.add_option(
439 action='store_true', dest='getdescription', default=False,
440 help='simulate, quiet but print video description')
441 verbosity.add_option(
443 action='store_true', dest='getduration', default=False,
444 help='simulate, quiet but print video length')
445 verbosity.add_option(
447 action='store_true', dest='getfilename', default=False,
448 help='simulate, quiet but print output filename')
449 verbosity.add_option(
451 action='store_true', dest='getformat', default=False,
452 help='simulate, quiet but print output format')
453 verbosity.add_option(
455 action='store_true', dest='dumpjson', default=False,
456 help='simulate, quiet but print JSON information. See --output for a description of available keys.')
457 verbosity.add_option(
458 '-J', '--dump-single-json',
459 action='store_true', dest='dump_single_json', default=False,
460 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.')
461 verbosity.add_option(
463 action='store_true', dest='print_json', default=False,
464 help='Be quiet and print the video information as JSON (video is still being downloaded).',
466 verbosity.add_option(
468 action='store_true', dest='progress_with_newline', default=False,
469 help='output progress bar as new lines')
470 verbosity.add_option(
472 action='store_true', dest='noprogress', default=False,
473 help='do not print progress bar')
474 verbosity.add_option(
476 action='store_true', dest='consoletitle', default=False,
477 help='display progress in console titlebar')
478 verbosity.add_option(
480 action='store_true', dest='verbose', default=False,
481 help='print various debugging information')
482 verbosity.add_option(
483 '--dump-intermediate-pages',
484 action='store_true', dest='dump_intermediate_pages', default=False,
485 help='print downloaded pages to debug problems (very verbose)')
486 verbosity.add_option(
488 action='store_true', dest='write_pages', default=False,
489 help='Write downloaded intermediary pages to files in the current directory to debug problems')
490 verbosity.add_option(
491 '--youtube-print-sig-code',
492 action='store_true', dest='youtube_print_sig_code', default=False,
493 help=optparse.SUPPRESS_HELP)
494 verbosity.add_option(
496 dest='debug_printtraffic', action='store_true', default=False,
497 help='Display sent and read HTTP traffic')
499 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
500 filesystem.add_option(
501 '-a', '--batch-file',
502 dest='batchfile', metavar='FILE',
503 help='file containing URLs to download (\'-\' for stdin)')
504 filesystem.add_option(
505 '--id', default=False,
506 action='store_true', dest='useid', help='use only video ID in file name')
507 filesystem.add_option(
509 dest='outtmpl', metavar='TEMPLATE',
510 help=('output filename template. Use %(title)s to get the title, '
511 '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
512 '%(autonumber)s to get an automatically incremented number, '
513 '%(ext)s for the filename extension, '
514 '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
515 '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
516 '%(upload_date)s for the upload date (YYYYMMDD), '
517 '%(extractor)s for the provider (youtube, metacafe, etc), '
518 '%(id)s for the video id, '
519 '%(playlist_title)s, %(playlist_id)s, or %(playlist)s (=title if present, ID otherwise) for the playlist the video is in, '
520 '%(playlist_index)s for the position in the playlist. '
521 '%(height)s and %(width)s for the width and height of the video format. '
522 '%(resolution)s for a textual description of the resolution of the video format. '
523 '%% for a literal percent. '
524 'Use - to output to stdout. Can also be used to download to a different directory, '
525 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
526 filesystem.add_option(
528 dest='autonumber_size', metavar='NUMBER',
529 help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
530 filesystem.add_option(
531 '--restrict-filenames',
532 action='store_true', dest='restrictfilenames', default=False,
533 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
534 filesystem.add_option(
535 '-A', '--auto-number',
536 action='store_true', dest='autonumber', default=False,
537 help='[deprecated; use -o "%(autonumber)s-%(title)s.%(ext)s" ] number downloaded files starting from 00000')
538 filesystem.add_option(
540 action='store_true', dest='usetitle', default=False,
541 help='[deprecated] use title in file name (default)')
542 filesystem.add_option(
543 '-l', '--literal', default=False,
544 action='store_true', dest='usetitle',
545 help='[deprecated] alias of --title')
546 filesystem.add_option(
547 '-w', '--no-overwrites',
548 action='store_true', dest='nooverwrites', default=False,
549 help='do not overwrite files')
550 filesystem.add_option(
552 action='store_true', dest='continue_dl', default=True,
553 help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
554 filesystem.add_option(
556 action='store_false', dest='continue_dl',
557 help='do not resume partially downloaded files (restart from beginning)')
558 filesystem.add_option(
560 action='store_true', dest='nopart', default=False,
561 help='do not use .part files - write directly into output file')
562 filesystem.add_option(
564 action='store_false', dest='updatetime', default=True,
565 help='do not use the Last-modified header to set the file modification time')
566 filesystem.add_option(
567 '--write-description',
568 action='store_true', dest='writedescription', default=False,
569 help='write video description to a .description file')
570 filesystem.add_option(
572 action='store_true', dest='writeinfojson', default=False,
573 help='write video metadata to a .info.json file')
574 filesystem.add_option(
575 '--write-annotations',
576 action='store_true', dest='writeannotations', default=False,
577 help='write video annotations to a .annotation file')
578 filesystem.add_option(
580 action='store_true', dest='writethumbnail', default=False,
581 help='write thumbnail image to disk')
582 filesystem.add_option(
584 dest='load_info_filename', metavar='FILE',
585 help='json file containing the video information (created with the "--write-json" option)')
586 filesystem.add_option(
588 dest='cookiefile', metavar='FILE',
589 help='file to read cookies from and dump cookie jar in')
590 filesystem.add_option(
591 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
592 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.')
593 filesystem.add_option(
594 '--no-cache-dir', action='store_const', const=False, dest='cachedir',
595 help='Disable filesystem caching')
596 filesystem.add_option(
598 action='store_true', dest='rm_cachedir',
599 help='Delete all filesystem cache files')
601 postproc = optparse.OptionGroup(parser, 'Post-processing Options')
603 '-x', '--extract-audio',
604 action='store_true', dest='extractaudio', default=False,
605 help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
607 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
608 help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default')
610 '--audio-quality', metavar='QUALITY',
611 dest='audioquality', default='5',
612 help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
615 metavar='FORMAT', dest='recodevideo', default=None,
616 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv)')
618 '-k', '--keep-video',
619 action='store_true', dest='keepvideo', default=False,
620 help='keeps the video file on disk after the post-processing; the video is erased by default')
622 '--no-post-overwrites',
623 action='store_true', dest='nopostoverwrites', default=False,
624 help='do not overwrite post-processed files; the post-processed files are overwritten by default')
627 action='store_true', dest='embedsubtitles', default=False,
628 help='embed subtitles in the video (only for mp4 videos)')
631 action='store_true', dest='embedthumbnail', default=False,
632 help='embed thumbnail in the audio as cover art')
635 action='store_true', dest='addmetadata', default=False,
636 help='write metadata to the video file')
639 action='store_true', dest='xattrs', default=False,
640 help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
643 metavar='POLICY', dest='fixup', default='detect_or_warn',
644 help='(experimental) Automatically correct known faults of the file. '
645 'One of never (do nothing), warn (only emit a warning), '
646 'detect_or_warn(check whether we can do anything about it, warn '
650 action='store_false', dest='prefer_ffmpeg',
651 help='Prefer avconv over ffmpeg for running the postprocessors (default)')
654 action='store_true', dest='prefer_ffmpeg',
655 help='Prefer ffmpeg over avconv for running the postprocessors')
658 metavar='CMD', dest='exec_cmd',
659 help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
661 parser.add_option_group(general)
662 parser.add_option_group(network)
663 parser.add_option_group(selection)
664 parser.add_option_group(downloader)
665 parser.add_option_group(filesystem)
666 parser.add_option_group(verbosity)
667 parser.add_option_group(workarounds)
668 parser.add_option_group(video_format)
669 parser.add_option_group(subtitles)
670 parser.add_option_group(authentication)
671 parser.add_option_group(postproc)
673 if overrideArguments is not None:
674 opts, args = parser.parse_args(overrideArguments)
676 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
678 commandLineConf = sys.argv[1:]
679 if '--ignore-config' in commandLineConf:
683 systemConf = _readOptions('/etc/youtube-dl.conf')
684 if '--ignore-config' in systemConf:
687 userConf = _readUserConf()
688 argv = systemConf + userConf + commandLineConf
690 opts, args = parser.parse_args(argv)
692 write_string('[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
693 write_string('[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
694 write_string('[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
696 return parser, opts, args