1 from __future__
import unicode_literals
12 from .version
import __version__
15 def parseOpts(overrideArguments
=None):
16 def _readOptions(filename_bytes
, default
=[]):
18 optionf
= open(filename_bytes
)
20 return default
# silently skip if file is not present
24 res
+= shlex
.split(l
, comments
=True)
30 xdg_config_home
= os
.environ
.get('XDG_CONFIG_HOME')
32 userConfFile
= os
.path
.join(xdg_config_home
, 'youtube-dl', 'config')
33 if not os
.path
.isfile(userConfFile
):
34 userConfFile
= os
.path
.join(xdg_config_home
, 'youtube-dl.conf')
36 userConfFile
= os
.path
.join(os
.path
.expanduser('~'), '.config', 'youtube-dl', 'config')
37 if not os
.path
.isfile(userConfFile
):
38 userConfFile
= os
.path
.join(os
.path
.expanduser('~'), '.config', 'youtube-dl.conf')
39 userConf
= _readOptions(userConfFile
, None)
42 appdata_dir
= os
.environ
.get('appdata')
44 userConf
= _readOptions(
45 os
.path
.join(appdata_dir
, 'youtube-dl', 'config'),
48 userConf
= _readOptions(
49 os
.path
.join(appdata_dir
, 'youtube-dl', 'config.txt'),
53 userConf
= _readOptions(
54 os
.path
.join(os
.path
.expanduser('~'), 'youtube-dl.conf'),
57 userConf
= _readOptions(
58 os
.path
.join(os
.path
.expanduser('~'), 'youtube-dl.conf.txt'),
66 def _format_option_string(option
):
67 ''' ('-o', '--option') -> -o, --format METAVAR'''
71 if option
._short
_opts
:
72 opts
.append(option
._short
_opts
[0])
74 opts
.append(option
._long
_opts
[0])
78 if option
.takes_value():
79 opts
.append(' %s' % option
.metavar
)
83 def _comma_separated_values_options_callback(option
, opt_str
, value
, parser
):
84 setattr(parser
.values
, option
.dest
, value
.split(','))
86 def _hide_login_info(opts
):
88 for private_opt
in ['-p', '--password', '-u', '--username', '--video-password']:
90 i
= opts
.index(private_opt
)
91 opts
[i
+ 1] = 'PRIVATE'
96 # No need to wrap help messages if we're on a wide console
97 columns
= get_term_width()
98 max_width
= columns
if columns
else 80
99 max_help_position
= 80
101 fmt
= optparse
.IndentedHelpFormatter(width
=max_width
, max_help_position
=max_help_position
)
102 fmt
.format_option_strings
= _format_option_string
105 'version': __version__
,
107 'usage': '%prog [options] url [url...]',
108 'conflict_handler': 'resolve',
111 parser
= optparse
.OptionParser(**kw
)
113 general
= optparse
.OptionGroup(parser
, 'General Options')
117 help='print this help text and exit')
121 help='print program version and exit')
124 action
='store_true', dest
='update_self',
125 help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
127 '-i', '--ignore-errors',
128 action
='store_true', dest
='ignoreerrors', default
=False,
129 help='continue on download errors, for example to skip unavailable videos in a playlist')
132 action
='store_false', dest
='ignoreerrors',
133 help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
136 action
='store_true', dest
='dump_user_agent', default
=False,
137 help='display the current browser identification')
140 action
='store_true', dest
='list_extractors', default
=False,
141 help='List all supported extractors and the URLs they would handle')
143 '--extractor-descriptions',
144 action
='store_true', dest
='list_extractor_descriptions', default
=False,
145 help='Output descriptions of all supported extractors')
147 '--proxy', dest
='proxy',
148 default
=None, metavar
='URL',
149 help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
152 dest
='socket_timeout', type=float, default
=None,
153 help='Time to wait before giving up, in seconds')
156 dest
='default_search', metavar
='PREFIX',
157 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.')
161 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)')
164 action
='store_const', dest
='extract_flat', const
='in_playlist',
166 help='Do not extract the videos of a playlist, only list them.')
168 selection
= optparse
.OptionGroup(parser
, 'Video Selection')
169 selection
.add_option(
171 dest
='playliststart', metavar
='NUMBER', default
=1, type=int,
172 help='playlist video to start at (default is %default)')
173 selection
.add_option(
175 dest
='playlistend', metavar
='NUMBER', default
=None, type=int,
176 help='playlist video to end at (default is last)')
177 selection
.add_option(
179 dest
='matchtitle', metavar
='REGEX',
180 help='download only matching titles (regex or caseless sub-string)')
181 selection
.add_option(
183 dest
='rejecttitle', metavar
='REGEX',
184 help='skip download for matching titles (regex or caseless sub-string)')
185 selection
.add_option(
187 dest
='max_downloads', metavar
='NUMBER', type=int, default
=None,
188 help='Abort after downloading NUMBER files')
189 selection
.add_option(
191 metavar
='SIZE', dest
='min_filesize', default
=None,
192 help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
193 selection
.add_option(
195 metavar
='SIZE', dest
='max_filesize', default
=None,
196 help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
197 selection
.add_option(
199 metavar
='DATE', dest
='date', default
=None,
200 help='download only videos uploaded in this date')
201 selection
.add_option(
203 metavar
='DATE', dest
='datebefore', default
=None,
204 help='download only videos uploaded on or before this date (i.e. inclusive)')
205 selection
.add_option(
207 metavar
='DATE', dest
='dateafter', default
=None,
208 help='download only videos uploaded on or after this date (i.e. inclusive)')
209 selection
.add_option(
211 metavar
='COUNT', dest
='min_views', default
=None, type=int,
212 help='Do not download any videos with less than COUNT views',)
213 selection
.add_option(
215 metavar
='COUNT', dest
='max_views', default
=None, type=int,
216 help='Do not download any videos with more than COUNT views')
217 selection
.add_option(
219 action
='store_true', dest
='noplaylist', default
=False,
220 help='download only the currently playing video')
221 selection
.add_option(
223 metavar
='YEARS', dest
='age_limit', default
=None, type=int,
224 help='download only videos suitable for the given age')
225 selection
.add_option(
226 '--download-archive', metavar
='FILE',
227 dest
='download_archive',
228 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
229 selection
.add_option(
231 dest
='include_ads', action
='store_true',
232 help='Download advertisements as well (experimental)')
234 authentication
= optparse
.OptionGroup(parser
, 'Authentication Options')
235 authentication
.add_option(
237 dest
='username', metavar
='USERNAME',
238 help='login with this account ID')
239 authentication
.add_option(
241 dest
='password', metavar
='PASSWORD',
242 help='account password')
243 authentication
.add_option(
245 dest
='twofactor', metavar
='TWOFACTOR',
246 help='two-factor auth code')
247 authentication
.add_option(
249 action
='store_true', dest
='usenetrc', default
=False,
250 help='use .netrc authentication data')
251 authentication
.add_option(
253 dest
='videopassword', metavar
='PASSWORD',
254 help='video password (vimeo, smotri)')
256 video_format
= optparse
.OptionGroup(parser
, 'Video Format Options')
257 video_format
.add_option(
259 action
='store', dest
='format', metavar
='FORMAT', default
=None,
260 help='video format code, specify the order of preference using slashes: -f 22/17/18 . -f mp4 , -f m4a and -f flv are also supported. You can also use the special names "best", "bestvideo", "bestaudio", "worst", "worstvideo" and "worstaudio". By default, youtube-dl will pick the best quality. Use commas to download multiple audio formats, such as -f 136/137/mp4/bestvideo,140/m4a/bestaudio')
261 video_format
.add_option(
263 action
='store_const', dest
='format', const
='all',
264 help='download all available video formats')
265 video_format
.add_option(
266 '--prefer-free-formats',
267 action
='store_true', dest
='prefer_free_formats', default
=False,
268 help='prefer free video formats unless a specific one is requested')
269 video_format
.add_option(
271 action
='store', dest
='format_limit', metavar
='FORMAT',
272 help='highest quality format to download')
273 video_format
.add_option(
274 '-F', '--list-formats',
275 action
='store_true', dest
='listformats',
276 help='list all available formats')
277 video_format
.add_option(
278 '--youtube-include-dash-manifest',
279 action
='store_true', dest
='youtube_include_dash_manifest', default
=True,
280 help=optparse
.SUPPRESS_HELP
)
281 video_format
.add_option(
282 '--youtube-skip-dash-manifest',
283 action
='store_false', dest
='youtube_include_dash_manifest',
284 help='Do not download the DASH manifest on YouTube videos')
286 subtitles
= optparse
.OptionGroup(parser
, 'Subtitle Options')
287 subtitles
.add_option(
288 '--write-sub', '--write-srt',
289 action
='store_true', dest
='writesubtitles', default
=False,
290 help='write subtitle file')
291 subtitles
.add_option(
292 '--write-auto-sub', '--write-automatic-sub',
293 action
='store_true', dest
='writeautomaticsub', default
=False,
294 help='write automatic subtitle file (youtube only)')
295 subtitles
.add_option(
297 action
='store_true', dest
='allsubtitles', default
=False,
298 help='downloads all the available subtitles of the video')
299 subtitles
.add_option(
301 action
='store_true', dest
='listsubtitles', default
=False,
302 help='lists all available subtitles for the video')
303 subtitles
.add_option(
305 action
='store', dest
='subtitlesformat', metavar
='FORMAT', default
='srt',
306 help='subtitle format (default=srt) ([sbv/vtt] youtube only)')
307 subtitles
.add_option(
308 '--sub-lang', '--sub-langs', '--srt-lang',
309 action
='callback', dest
='subtitleslangs', metavar
='LANGS', type='str',
310 default
=[], callback
=_comma_separated_values_options_callback
,
311 help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
313 downloader
= optparse
.OptionGroup(parser
, 'Download Options')
314 downloader
.add_option(
315 '-r', '--rate-limit',
316 dest
='ratelimit', metavar
='LIMIT',
317 help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
318 downloader
.add_option(
320 dest
='retries', metavar
='RETRIES', default
=10,
321 help='number of retries (default is %default)')
322 downloader
.add_option(
324 dest
='buffersize', metavar
='SIZE', default
='1024',
325 help='size of download buffer (e.g. 1024 or 16K) (default is %default)')
326 downloader
.add_option(
327 '--no-resize-buffer',
328 action
='store_true', dest
='noresizebuffer', default
=False,
329 help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
330 downloader
.add_option(
332 action
='store_true', dest
='test', default
=False,
333 help=optparse
.SUPPRESS_HELP
)
335 workarounds
= optparse
.OptionGroup(parser
, 'Workarounds')
336 workarounds
.add_option(
338 dest
='encoding', metavar
='ENCODING',
339 help='Force the specified encoding (experimental)')
340 workarounds
.add_option(
341 '--no-check-certificate',
342 action
='store_true', dest
='no_check_certificate', default
=False,
343 help='Suppress HTTPS certificate validation.')
344 workarounds
.add_option(
346 '--prefer-unsecure', action
='store_true', dest
='prefer_insecure',
347 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
348 workarounds
.add_option(
350 metavar
='UA', dest
='user_agent',
351 help='specify a custom user agent')
352 workarounds
.add_option(
354 metavar
='URL', dest
='referer', default
=None,
355 help='specify a custom referer, use if the video access is restricted to one domain',
357 workarounds
.add_option(
359 metavar
='FIELD:VALUE', dest
='headers', action
='append',
360 help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
362 workarounds
.add_option(
364 dest
='bidi_workaround', action
='store_true',
365 help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
367 verbosity
= optparse
.OptionGroup(parser
, 'Verbosity / Simulation Options')
368 verbosity
.add_option(
370 action
='store_true', dest
='quiet', default
=False,
371 help='activates quiet mode')
372 verbosity
.add_option(
374 dest
='no_warnings', action
='store_true', default
=False,
375 help='Ignore warnings')
376 verbosity
.add_option(
378 action
='store_true', dest
='simulate', default
=False,
379 help='do not download the video and do not write anything to disk',)
380 verbosity
.add_option(
382 action
='store_true', dest
='skip_download', default
=False,
383 help='do not download the video',)
384 verbosity
.add_option(
386 action
='store_true', dest
='geturl', default
=False,
387 help='simulate, quiet but print URL')
388 verbosity
.add_option(
390 action
='store_true', dest
='gettitle', default
=False,
391 help='simulate, quiet but print title')
392 verbosity
.add_option(
394 action
='store_true', dest
='getid', default
=False,
395 help='simulate, quiet but print id')
396 verbosity
.add_option(
398 action
='store_true', dest
='getthumbnail', default
=False,
399 help='simulate, quiet but print thumbnail URL')
400 verbosity
.add_option(
402 action
='store_true', dest
='getdescription', default
=False,
403 help='simulate, quiet but print video description')
404 verbosity
.add_option(
406 action
='store_true', dest
='getduration', default
=False,
407 help='simulate, quiet but print video length')
408 verbosity
.add_option(
410 action
='store_true', dest
='getfilename', default
=False,
411 help='simulate, quiet but print output filename')
412 verbosity
.add_option(
414 action
='store_true', dest
='getformat', default
=False,
415 help='simulate, quiet but print output format')
416 verbosity
.add_option(
418 action
='store_true', dest
='dumpjson', default
=False,
419 help='simulate, quiet but print JSON information. See --output for a description of available keys.')
420 verbosity
.add_option(
422 action
='store_true', dest
='progress_with_newline', default
=False,
423 help='output progress bar as new lines')
424 verbosity
.add_option(
426 action
='store_true', dest
='noprogress', default
=False,
427 help='do not print progress bar')
428 verbosity
.add_option(
430 action
='store_true', dest
='consoletitle', default
=False,
431 help='display progress in console titlebar')
432 verbosity
.add_option(
434 action
='store_true', dest
='verbose', default
=False,
435 help='print various debugging information')
436 verbosity
.add_option(
437 '--dump-intermediate-pages',
438 action
='store_true', dest
='dump_intermediate_pages', default
=False,
439 help='print downloaded pages to debug problems (very verbose)')
440 verbosity
.add_option(
442 action
='store_true', dest
='write_pages', default
=False,
443 help='Write downloaded intermediary pages to files in the current directory to debug problems')
444 verbosity
.add_option(
445 '--youtube-print-sig-code',
446 action
='store_true', dest
='youtube_print_sig_code', default
=False,
447 help=optparse
.SUPPRESS_HELP
)
448 verbosity
.add_option(
450 dest
='debug_printtraffic', action
='store_true', default
=False,
451 help='Display sent and read HTTP traffic')
453 filesystem
= optparse
.OptionGroup(parser
, 'Filesystem Options')
454 filesystem
.add_option(
455 '-a', '--batch-file',
456 dest
='batchfile', metavar
='FILE',
457 help='file containing URLs to download (\'-\' for stdin)')
458 filesystem
.add_option(
459 '--id', default
=False,
460 action
='store_true', dest
='useid', help='use only video ID in file name')
461 filesystem
.add_option(
462 '-A', '--auto-number',
463 action
='store_true', dest
='autonumber', default
=False,
464 help='number downloaded files starting from 00000')
465 filesystem
.add_option(
467 dest
='outtmpl', metavar
='TEMPLATE',
468 help=('output filename template. Use %(title)s to get the title, '
469 '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
470 '%(autonumber)s to get an automatically incremented number, '
471 '%(ext)s for the filename extension, '
472 '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
473 '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
474 '%(upload_date)s for the upload date (YYYYMMDD), '
475 '%(extractor)s for the provider (youtube, metacafe, etc), '
476 '%(id)s for the video id, %(playlist)s for the playlist the video is in, '
477 '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
478 '%(height)s and %(width)s for the width and height of the video format. '
479 '%(resolution)s for a textual description of the resolution of the video format. '
480 'Use - to output to stdout. Can also be used to download to a different directory, '
481 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
482 filesystem
.add_option(
484 dest
='autonumber_size', metavar
='NUMBER',
485 help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
486 filesystem
.add_option(
487 '--restrict-filenames',
488 action
='store_true', dest
='restrictfilenames', default
=False,
489 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
490 filesystem
.add_option(
492 action
='store_true', dest
='usetitle', default
=False,
493 help='[deprecated] use title in file name (default)')
494 filesystem
.add_option(
495 '-l', '--literal', default
=False,
496 action
='store_true', dest
='usetitle',
497 help='[deprecated] alias of --title')
498 filesystem
.add_option(
499 '-w', '--no-overwrites',
500 action
='store_true', dest
='nooverwrites', default
=False,
501 help='do not overwrite files')
502 filesystem
.add_option(
504 action
='store_true', dest
='continue_dl', default
=True,
505 help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
506 filesystem
.add_option(
508 action
='store_false', dest
='continue_dl',
509 help='do not resume partially downloaded files (restart from beginning)')
510 filesystem
.add_option(
512 action
='store_true', dest
='nopart', default
=False,
513 help='do not use .part files - write directly into output file')
514 filesystem
.add_option(
516 action
='store_false', dest
='updatetime', default
=True,
517 help='do not use the Last-modified header to set the file modification time')
518 filesystem
.add_option(
519 '--write-description',
520 action
='store_true', dest
='writedescription', default
=False,
521 help='write video description to a .description file')
522 filesystem
.add_option(
524 action
='store_true', dest
='writeinfojson', default
=False,
525 help='write video metadata to a .info.json file')
526 filesystem
.add_option(
527 '--write-annotations',
528 action
='store_true', dest
='writeannotations', default
=False,
529 help='write video annotations to a .annotation file')
530 filesystem
.add_option(
532 action
='store_true', dest
='writethumbnail', default
=False,
533 help='write thumbnail image to disk')
534 filesystem
.add_option(
536 dest
='load_info_filename', metavar
='FILE',
537 help='json file containing the video information (created with the "--write-json" option)')
538 filesystem
.add_option(
540 dest
='cookiefile', metavar
='FILE',
541 help='file to read cookies from and dump cookie jar in')
542 filesystem
.add_option(
543 '--cache-dir', dest
='cachedir', default
=None, metavar
='DIR',
544 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.')
545 filesystem
.add_option(
546 '--no-cache-dir', action
='store_const', const
=False, dest
='cachedir',
547 help='Disable filesystem caching')
548 filesystem
.add_option(
550 action
='store_true', dest
='rm_cachedir',
551 help='Delete all filesystem cache files')
553 postproc
= optparse
.OptionGroup(parser
, 'Post-processing Options')
555 '-x', '--extract-audio',
556 action
='store_true', dest
='extractaudio', default
=False,
557 help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
559 '--audio-format', metavar
='FORMAT', dest
='audioformat', default
='best',
560 help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; "%default" by default')
562 '--audio-quality', metavar
='QUALITY',
563 dest
='audioquality', default
='5',
564 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)')
567 metavar
='FORMAT', dest
='recodevideo', default
=None,
568 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv)')
570 '-k', '--keep-video',
571 action
='store_true', dest
='keepvideo', default
=False,
572 help='keeps the video file on disk after the post-processing; the video is erased by default')
574 '--no-post-overwrites',
575 action
='store_true', dest
='nopostoverwrites', default
=False,
576 help='do not overwrite post-processed files; the post-processed files are overwritten by default')
579 action
='store_true', dest
='embedsubtitles', default
=False,
580 help='embed subtitles in the video (only for mp4 videos)')
583 action
='store_true', dest
='embedthumbnail', default
=False,
584 help='embed thumbnail in the audio as cover art')
587 action
='store_true', dest
='addmetadata', default
=False,
588 help='write metadata to the video file')
591 action
='store_true', dest
='xattrs', default
=False,
592 help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
595 action
='store_false', dest
='prefer_ffmpeg',
596 help='Prefer avconv over ffmpeg for running the postprocessors (default)')
599 action
='store_true', dest
='prefer_ffmpeg',
600 help='Prefer ffmpeg over avconv for running the postprocessors')
603 metavar
='CMD', dest
='exec_cmd',
604 help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'' )
606 parser
.add_option_group(general
)
607 parser
.add_option_group(selection
)
608 parser
.add_option_group(downloader
)
609 parser
.add_option_group(filesystem
)
610 parser
.add_option_group(verbosity
)
611 parser
.add_option_group(workarounds
)
612 parser
.add_option_group(video_format
)
613 parser
.add_option_group(subtitles
)
614 parser
.add_option_group(authentication
)
615 parser
.add_option_group(postproc
)
617 if overrideArguments
is not None:
618 opts
, args
= parser
.parse_args(overrideArguments
)
620 write_string('[debug] Override config: ' + repr(overrideArguments
) + '\n')
622 commandLineConf
= sys
.argv
[1:]
623 if '--ignore-config' in commandLineConf
:
627 systemConf
= _readOptions('/etc/youtube-dl.conf')
628 if '--ignore-config' in systemConf
:
631 userConf
= _readUserConf()
632 argv
= systemConf
+ userConf
+ commandLineConf
634 opts
, args
= parser
.parse_args(argv
)
636 write_string('[debug] System config: ' + repr(_hide_login_info(systemConf
)) + '\n')
637 write_string('[debug] User config: ' + repr(_hide_login_info(userConf
)) + '\n')
638 write_string('[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf
)) + '\n')
640 return parser
, opts
, args