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')
152 '--proxy', dest='proxy',
153 default=None, metavar='URL',
154 help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
157 dest='socket_timeout', type=float, default=None,
158 help='Time to wait before giving up, in seconds')
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.')
166 help='Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: do not read the user configuration in ~/.config/youtube-dl.conf (%APPDATA%/youtube-dl/config.txt on Windows)')
169 action='store_const', dest='extract_flat', const='in_playlist',
171 help='Do not extract the videos of a playlist, only list them.')
173 selection = optparse.OptionGroup(parser, 'Video Selection')
174 selection.add_option(
176 dest='playliststart', metavar='NUMBER', default=1, type=int,
177 help='playlist video to start at (default is %default)')
178 selection.add_option(
180 dest='playlistend', metavar='NUMBER', default=None, type=int,
181 help='playlist video to end at (default is last)')
182 selection.add_option(
184 dest='matchtitle', metavar='REGEX',
185 help='download only matching titles (regex or caseless sub-string)')
186 selection.add_option(
188 dest='rejecttitle', metavar='REGEX',
189 help='skip download for matching titles (regex or caseless sub-string)')
190 selection.add_option(
192 dest='max_downloads', metavar='NUMBER', type=int, default=None,
193 help='Abort after downloading NUMBER files')
194 selection.add_option(
196 metavar='SIZE', dest='min_filesize', default=None,
197 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
198 selection.add_option(
200 metavar='SIZE', dest='max_filesize', default=None,
201 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
202 selection.add_option(
204 metavar='DATE', dest='date', default=None,
205 help='download only videos uploaded in this date')
206 selection.add_option(
208 metavar='DATE', dest='datebefore', default=None,
209 help='download only videos uploaded on or before this date (i.e. inclusive)')
210 selection.add_option(
212 metavar='DATE', dest='dateafter', default=None,
213 help='download only videos uploaded on or after this date (i.e. inclusive)')
214 selection.add_option(
216 metavar='COUNT', dest='min_views', default=None, type=int,
217 help='Do not download any videos with less than COUNT views',)
218 selection.add_option(
220 metavar='COUNT', dest='max_views', default=None, type=int,
221 help='Do not download any videos with more than COUNT views')
222 selection.add_option(
224 action='store_true', dest='noplaylist', default=False,
225 help='download only the currently playing video')
226 selection.add_option(
228 metavar='YEARS', dest='age_limit', default=None, type=int,
229 help='download only videos suitable for the given age')
230 selection.add_option(
231 '--download-archive', metavar='FILE',
232 dest='download_archive',
233 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
234 selection.add_option(
236 dest='include_ads', action='store_true',
237 help='Download advertisements as well (experimental)')
239 authentication = optparse.OptionGroup(parser, 'Authentication Options')
240 authentication.add_option(
242 dest='username', metavar='USERNAME',
243 help='login with this account ID')
244 authentication.add_option(
246 dest='password', metavar='PASSWORD',
247 help='account password')
248 authentication.add_option(
250 dest='twofactor', metavar='TWOFACTOR',
251 help='two-factor auth code')
252 authentication.add_option(
254 action='store_true', dest='usenetrc', default=False,
255 help='use .netrc authentication data')
256 authentication.add_option(
258 dest='videopassword', metavar='PASSWORD',
259 help='video password (vimeo, smotri)')
261 video_format = optparse.OptionGroup(parser, 'Video Format Options')
262 video_format.add_option(
264 action='store', dest='format', metavar='FORMAT', default=None,
265 help='video format code, specify the order of preference using'
266 ' slashes: -f 22/17/18 . -f mp4 , -f m4a and -f flv are also'
267 ' supported. You can also use the special names "best",'
268 ' "bestvideo", "bestaudio", "worst", "worstvideo" and'
269 ' "worstaudio". By default, youtube-dl will pick the best quality.'
270 ' Use commas to download multiple audio formats, such as'
271 ' -f 136/137/mp4/bestvideo,140/m4a/bestaudio.'
272 ' You can merge the video and audio of two formats into a single'
273 ' file using -f <video-format>+<audio-format> (requires ffmpeg or'
274 ' avconv), for example -f bestvideo+bestaudio.')
275 video_format.add_option(
277 action='store_const', dest='format', const='all',
278 help='download all available video formats')
279 video_format.add_option(
280 '--prefer-free-formats',
281 action='store_true', dest='prefer_free_formats', default=False,
282 help='prefer free video formats unless a specific one is requested')
283 video_format.add_option(
285 action='store', dest='format_limit', metavar='FORMAT',
286 help='highest quality format to download')
287 video_format.add_option(
288 '-F', '--list-formats',
289 action='store_true', dest='listformats',
290 help='list all available formats')
291 video_format.add_option(
292 '--youtube-include-dash-manifest',
293 action='store_true', dest='youtube_include_dash_manifest', default=True,
294 help=optparse.SUPPRESS_HELP)
295 video_format.add_option(
296 '--youtube-skip-dash-manifest',
297 action='store_false', dest='youtube_include_dash_manifest',
298 help='Do not download the DASH manifest on YouTube videos')
300 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
301 subtitles.add_option(
302 '--write-sub', '--write-srt',
303 action='store_true', dest='writesubtitles', default=False,
304 help='write subtitle file')
305 subtitles.add_option(
306 '--write-auto-sub', '--write-automatic-sub',
307 action='store_true', dest='writeautomaticsub', default=False,
308 help='write automatic subtitle file (youtube only)')
309 subtitles.add_option(
311 action='store_true', dest='allsubtitles', default=False,
312 help='downloads all the available subtitles of the video')
313 subtitles.add_option(
315 action='store_true', dest='listsubtitles', default=False,
316 help='lists all available subtitles for the video')
317 subtitles.add_option(
319 action='store', dest='subtitlesformat', metavar='FORMAT', default='srt',
320 help='subtitle format (default=srt) ([sbv/vtt] youtube only)')
321 subtitles.add_option(
322 '--sub-lang', '--sub-langs', '--srt-lang',
323 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
324 default=[], callback=_comma_separated_values_options_callback,
325 help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
327 downloader = optparse.OptionGroup(parser, 'Download Options')
328 downloader.add_option(
329 '-r', '--rate-limit',
330 dest='ratelimit', metavar='LIMIT',
331 help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
332 downloader.add_option(
334 dest='retries', metavar='RETRIES', default=10,
335 help='number of retries (default is %default)')
336 downloader.add_option(
338 dest='buffersize', metavar='SIZE', default='1024',
339 help='size of download buffer (e.g. 1024 or 16K) (default is %default)')
340 downloader.add_option(
341 '--no-resize-buffer',
342 action='store_true', dest='noresizebuffer', default=False,
343 help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
344 downloader.add_option(
346 action='store_true', dest='test', default=False,
347 help=optparse.SUPPRESS_HELP)
349 workarounds = optparse.OptionGroup(parser, 'Workarounds')
350 workarounds.add_option(
352 dest='encoding', metavar='ENCODING',
353 help='Force the specified encoding (experimental)')
354 workarounds.add_option(
355 '--no-check-certificate',
356 action='store_true', dest='no_check_certificate', default=False,
357 help='Suppress HTTPS certificate validation.')
358 workarounds.add_option(
360 '--prefer-unsecure', action='store_true', dest='prefer_insecure',
361 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
362 workarounds.add_option(
364 metavar='UA', dest='user_agent',
365 help='specify a custom user agent')
366 workarounds.add_option(
368 metavar='URL', dest='referer', default=None,
369 help='specify a custom referer, use if the video access is restricted to one domain',
371 workarounds.add_option(
373 metavar='FIELD:VALUE', dest='headers', action='append',
374 help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
376 workarounds.add_option(
378 dest='bidi_workaround', action='store_true',
379 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
381 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
382 verbosity.add_option(
384 action='store_true', dest='quiet', default=False,
385 help='activates quiet mode')
386 verbosity.add_option(
388 dest='no_warnings', action='store_true', default=False,
389 help='Ignore warnings')
390 verbosity.add_option(
392 action='store_true', dest='simulate', default=False,
393 help='do not download the video and do not write anything to disk',)
394 verbosity.add_option(
396 action='store_true', dest='skip_download', default=False,
397 help='do not download the video',)
398 verbosity.add_option(
400 action='store_true', dest='geturl', default=False,
401 help='simulate, quiet but print URL')
402 verbosity.add_option(
404 action='store_true', dest='gettitle', default=False,
405 help='simulate, quiet but print title')
406 verbosity.add_option(
408 action='store_true', dest='getid', default=False,
409 help='simulate, quiet but print id')
410 verbosity.add_option(
412 action='store_true', dest='getthumbnail', default=False,
413 help='simulate, quiet but print thumbnail URL')
414 verbosity.add_option(
416 action='store_true', dest='getdescription', default=False,
417 help='simulate, quiet but print video description')
418 verbosity.add_option(
420 action='store_true', dest='getduration', default=False,
421 help='simulate, quiet but print video length')
422 verbosity.add_option(
424 action='store_true', dest='getfilename', default=False,
425 help='simulate, quiet but print output filename')
426 verbosity.add_option(
428 action='store_true', dest='getformat', default=False,
429 help='simulate, quiet but print output format')
430 verbosity.add_option(
432 action='store_true', dest='dumpjson', default=False,
433 help='simulate, quiet but print JSON information. See --output for a description of available keys.')
434 verbosity.add_option(
435 '-J', '--dump-single-json',
436 action='store_true', dest='dump_single_json', default=False,
437 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.')
438 verbosity.add_option(
440 action='store_true', dest='progress_with_newline', default=False,
441 help='output progress bar as new lines')
442 verbosity.add_option(
444 action='store_true', dest='noprogress', default=False,
445 help='do not print progress bar')
446 verbosity.add_option(
448 action='store_true', dest='consoletitle', default=False,
449 help='display progress in console titlebar')
450 verbosity.add_option(
452 action='store_true', dest='verbose', default=False,
453 help='print various debugging information')
454 verbosity.add_option(
455 '--dump-intermediate-pages',
456 action='store_true', dest='dump_intermediate_pages', default=False,
457 help='print downloaded pages to debug problems (very verbose)')
458 verbosity.add_option(
460 action='store_true', dest='write_pages', default=False,
461 help='Write downloaded intermediary pages to files in the current directory to debug problems')
462 verbosity.add_option(
463 '--youtube-print-sig-code',
464 action='store_true', dest='youtube_print_sig_code', default=False,
465 help=optparse.SUPPRESS_HELP)
466 verbosity.add_option(
468 dest='debug_printtraffic', action='store_true', default=False,
469 help='Display sent and read HTTP traffic')
471 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
472 filesystem.add_option(
473 '-a', '--batch-file',
474 dest='batchfile', metavar='FILE',
475 help='file containing URLs to download (\'-\' for stdin)')
476 filesystem.add_option(
477 '--id', default=False,
478 action='store_true', dest='useid', help='use only video ID in file name')
479 filesystem.add_option(
480 '-A', '--auto-number',
481 action='store_true', dest='autonumber', default=False,
482 help='number downloaded files starting from 00000')
483 filesystem.add_option(
485 dest='outtmpl', metavar='TEMPLATE',
486 help=('output filename template. Use %(title)s to get the title, '
487 '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
488 '%(autonumber)s to get an automatically incremented number, '
489 '%(ext)s for the filename extension, '
490 '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
491 '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
492 '%(upload_date)s for the upload date (YYYYMMDD), '
493 '%(extractor)s for the provider (youtube, metacafe, etc), '
494 '%(id)s for the video id, '
495 '%(playlist_title)s, %(playlist_id)s, or %(playlist)s (=title if present, ID otherwise) for the playlist the video is in, '
496 '%(playlist_index)s for the position in the playlist. '
497 '%(height)s and %(width)s for the width and height of the video format. '
498 '%(resolution)s for a textual description of the resolution of the video format. '
499 '%% for a literal percent. '
500 'Use - to output to stdout. Can also be used to download to a different directory, '
501 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
502 filesystem.add_option(
504 dest='autonumber_size', metavar='NUMBER',
505 help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
506 filesystem.add_option(
507 '--restrict-filenames',
508 action='store_true', dest='restrictfilenames', default=False,
509 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
510 filesystem.add_option(
512 action='store_true', dest='usetitle', default=False,
513 help='[deprecated] use title in file name (default)')
514 filesystem.add_option(
515 '-l', '--literal', default=False,
516 action='store_true', dest='usetitle',
517 help='[deprecated] alias of --title')
518 filesystem.add_option(
519 '-w', '--no-overwrites',
520 action='store_true', dest='nooverwrites', default=False,
521 help='do not overwrite files')
522 filesystem.add_option(
524 action='store_true', dest='continue_dl', default=True,
525 help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
526 filesystem.add_option(
528 action='store_false', dest='continue_dl',
529 help='do not resume partially downloaded files (restart from beginning)')
530 filesystem.add_option(
532 action='store_true', dest='nopart', default=False,
533 help='do not use .part files - write directly into output file')
534 filesystem.add_option(
536 action='store_false', dest='updatetime', default=True,
537 help='do not use the Last-modified header to set the file modification time')
538 filesystem.add_option(
539 '--write-description',
540 action='store_true', dest='writedescription', default=False,
541 help='write video description to a .description file')
542 filesystem.add_option(
544 action='store_true', dest='writeinfojson', default=False,
545 help='write video metadata to a .info.json file')
546 filesystem.add_option(
547 '--write-annotations',
548 action='store_true', dest='writeannotations', default=False,
549 help='write video annotations to a .annotation file')
550 filesystem.add_option(
552 action='store_true', dest='writethumbnail', default=False,
553 help='write thumbnail image to disk')
554 filesystem.add_option(
556 dest='load_info_filename', metavar='FILE',
557 help='json file containing the video information (created with the "--write-json" option)')
558 filesystem.add_option(
560 dest='cookiefile', metavar='FILE',
561 help='file to read cookies from and dump cookie jar in')
562 filesystem.add_option(
563 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
564 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.')
565 filesystem.add_option(
566 '--no-cache-dir', action='store_const', const=False, dest='cachedir',
567 help='Disable filesystem caching')
568 filesystem.add_option(
570 action='store_true', dest='rm_cachedir',
571 help='Delete all filesystem cache files')
573 postproc = optparse.OptionGroup(parser, 'Post-processing Options')
575 '-x', '--extract-audio',
576 action='store_true', dest='extractaudio', default=False,
577 help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
579 '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
580 help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default')
582 '--audio-quality', metavar='QUALITY',
583 dest='audioquality', default='5',
584 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)')
587 metavar='FORMAT', dest='recodevideo', default=None,
588 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv)')
590 '-k', '--keep-video',
591 action='store_true', dest='keepvideo', default=False,
592 help='keeps the video file on disk after the post-processing; the video is erased by default')
594 '--no-post-overwrites',
595 action='store_true', dest='nopostoverwrites', default=False,
596 help='do not overwrite post-processed files; the post-processed files are overwritten by default')
599 action='store_true', dest='embedsubtitles', default=False,
600 help='embed subtitles in the video (only for mp4 videos)')
603 action='store_true', dest='embedthumbnail', default=False,
604 help='embed thumbnail in the audio as cover art')
607 action='store_true', dest='addmetadata', default=False,
608 help='write metadata to the video file')
611 action='store_true', dest='xattrs', default=False,
612 help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
615 action='store_false', dest='prefer_ffmpeg',
616 help='Prefer avconv over ffmpeg for running the postprocessors (default)')
619 action='store_true', dest='prefer_ffmpeg',
620 help='Prefer ffmpeg over avconv for running the postprocessors')
623 metavar='CMD', dest='exec_cmd',
624 help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'' )
626 parser.add_option_group(general)
627 parser.add_option_group(selection)
628 parser.add_option_group(downloader)
629 parser.add_option_group(filesystem)
630 parser.add_option_group(verbosity)
631 parser.add_option_group(workarounds)
632 parser.add_option_group(video_format)
633 parser.add_option_group(subtitles)
634 parser.add_option_group(authentication)
635 parser.add_option_group(postproc)
637 if overrideArguments is not None:
638 opts, args = parser.parse_args(overrideArguments)
640 write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
642 commandLineConf = sys.argv[1:]
643 if '--ignore-config' in commandLineConf:
647 systemConf = _readOptions('/etc/youtube-dl.conf')
648 if '--ignore-config' in systemConf:
651 userConf = _readUserConf()
652 argv = systemConf + userConf + commandLineConf
654 opts, args = parser.parse_args(argv)
656 write_string('[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
657 write_string('[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
658 write_string('[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
660 return parser, opts, args