10 from .version import __version__
13 def parseOpts(overrideArguments=None):
14 def _readOptions(filename_bytes, default=[]):
16 optionf = open(filename_bytes)
18 return default # silently skip if file is not present
22 res += shlex.split(l, comments=True)
28 xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
30 userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
31 if not os.path.isfile(userConfFile):
32 userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
34 userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl', 'config')
35 if not os.path.isfile(userConfFile):
36 userConfFile = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
37 userConf = _readOptions(userConfFile, None)
40 appdata_dir = os.environ.get('appdata')
42 userConf = _readOptions(
43 os.path.join(appdata_dir, 'youtube-dl', 'config'),
46 userConf = _readOptions(
47 os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
51 userConf = _readOptions(
52 os.path.join(os.path.expanduser('~'), 'youtube-dl.conf'),
55 userConf = _readOptions(
56 os.path.join(os.path.expanduser('~'), 'youtube-dl.conf.txt'),
64 def _format_option_string(option):
65 ''' ('-o', '--option') -> -o, --format METAVAR'''
69 if option._short_opts:
70 opts.append(option._short_opts[0])
72 opts.append(option._long_opts[0])
76 if option.takes_value(): opts.append(' %s' % option.metavar)
80 def _comma_separated_values_options_callback(option, opt_str, value, parser):
81 setattr(parser.values, option.dest, value.split(','))
83 def _hide_login_info(opts):
85 for private_opt in ['-p', '--password', '-u', '--username', '--video-password']:
87 i = opts.index(private_opt)
88 opts[i+1] = '<PRIVATE>'
94 max_help_position = 80
96 # No need to wrap help messages if we're on a wide console
97 columns = get_term_width()
98 if columns: max_width = columns
100 fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
101 fmt.format_option_strings = _format_option_string
104 'version' : __version__,
106 'usage' : '%prog [options] url [url...]',
107 'conflict_handler' : 'resolve',
110 parser = optparse.OptionParser(**kw)
113 general = optparse.OptionGroup(parser, 'General Options')
114 selection = optparse.OptionGroup(parser, 'Video Selection')
115 authentication = optparse.OptionGroup(parser, 'Authentication Options')
116 video_format = optparse.OptionGroup(parser, 'Video Format Options')
117 subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
118 downloader = optparse.OptionGroup(parser, 'Download Options')
119 postproc = optparse.OptionGroup(parser, 'Post-processing Options')
120 filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
121 workarounds = optparse.OptionGroup(parser, 'Workarounds')
122 verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
124 general.add_option('-h', '--help',
125 action='help', help='print this help text and exit')
126 general.add_option('-v', '--version',
127 action='version', help='print program version and exit')
128 general.add_option('-U', '--update',
129 action='store_true', dest='update_self', help='update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
130 general.add_option('-i', '--ignore-errors',
131 action='store_true', dest='ignoreerrors', help='continue on download errors, for example to skip unavailable videos in a playlist', default=False)
132 general.add_option('--abort-on-error',
133 action='store_false', dest='ignoreerrors',
134 help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
135 general.add_option('--dump-user-agent',
136 action='store_true', dest='dump_user_agent',
137 help='display the current browser identification', default=False)
138 general.add_option('--list-extractors',
139 action='store_true', dest='list_extractors',
140 help='List all supported extractors and the URLs they would handle', default=False)
141 general.add_option('--extractor-descriptions',
142 action='store_true', dest='list_extractor_descriptions',
143 help='Output descriptions of all supported extractors', default=False)
145 '--proxy', dest='proxy', default=None, metavar='URL',
146 help='Use the specified HTTP/HTTPS proxy. Pass in an empty string (--proxy "") for direct connection')
148 '--socket-timeout', dest='socket_timeout',
149 type=float, default=None, help=u'Time to wait before giving up, in seconds')
152 dest='default_search', metavar='PREFIX',
153 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.')
157 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)')
159 selection.add_option(
161 dest='playliststart', metavar='NUMBER', default=1, type=int,
162 help='playlist video to start at (default is %default)')
163 selection.add_option(
165 dest='playlistend', metavar='NUMBER', default=None, type=int,
166 help='playlist video to end at (default is last)')
167 selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
168 selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
169 selection.add_option('--max-downloads', metavar='NUMBER',
170 dest='max_downloads', type=int, default=None,
171 help='Abort after downloading NUMBER files')
172 selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
173 selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
174 selection.add_option('--date', metavar='DATE', dest='date', help='download only videos uploaded in this date', default=None)
175 selection.add_option(
176 '--datebefore', metavar='DATE', dest='datebefore', default=None,
177 help='download only videos uploaded on or before this date (i.e. inclusive)')
178 selection.add_option(
179 '--dateafter', metavar='DATE', dest='dateafter', default=None,
180 help='download only videos uploaded on or after this date (i.e. inclusive)')
181 selection.add_option(
182 '--min-views', metavar='COUNT', dest='min_views',
183 default=None, type=int,
184 help="Do not download any videos with less than COUNT views",)
185 selection.add_option(
186 '--max-views', metavar='COUNT', dest='max_views',
187 default=None, type=int,
188 help="Do not download any videos with more than COUNT views",)
189 selection.add_option('--no-playlist', action='store_true', dest='noplaylist', help='download only the currently playing video', default=False)
190 selection.add_option('--age-limit', metavar='YEARS', dest='age_limit',
191 help='download only videos suitable for the given age',
192 default=None, type=int)
193 selection.add_option('--download-archive', metavar='FILE',
194 dest='download_archive',
195 help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
196 selection.add_option(
197 '--include-ads', dest='include_ads',
199 help='Download advertisements as well (experimental)')
200 selection.add_option(
201 '--youtube-include-dash-manifest', action='store_true',
202 dest='youtube_include_dash_manifest', default=False,
203 help='Try to download the DASH manifest on YouTube videos (experimental)')
205 authentication.add_option('-u', '--username',
206 dest='username', metavar='USERNAME', help='account username')
207 authentication.add_option('-p', '--password',
208 dest='password', metavar='PASSWORD', help='account password')
209 authentication.add_option('-2', '--twofactor',
210 dest='twofactor', metavar='TWOFACTOR', help='two-factor auth code')
211 authentication.add_option('-n', '--netrc',
212 action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
213 authentication.add_option('--video-password',
214 dest='videopassword', metavar='PASSWORD', help='video password (vimeo, smotri)')
217 video_format.add_option('-f', '--format',
218 action='store', dest='format', metavar='FORMAT', default=None,
219 help='video format code, specify the order of preference using slashes: "-f 22/17/18". "-f mp4" 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.')
220 video_format.add_option('--all-formats',
221 action='store_const', dest='format', help='download all available video formats', const='all')
222 video_format.add_option('--prefer-free-formats',
223 action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
224 video_format.add_option('--max-quality',
225 action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
226 video_format.add_option('-F', '--list-formats',
227 action='store_true', dest='listformats', help='list all available formats')
229 subtitles.add_option('--write-sub', '--write-srt',
230 action='store_true', dest='writesubtitles',
231 help='write subtitle file', default=False)
232 subtitles.add_option('--write-auto-sub', '--write-automatic-sub',
233 action='store_true', dest='writeautomaticsub',
234 help='write automatic subtitle file (youtube only)', default=False)
235 subtitles.add_option('--all-subs',
236 action='store_true', dest='allsubtitles',
237 help='downloads all the available subtitles of the video', default=False)
238 subtitles.add_option('--list-subs',
239 action='store_true', dest='listsubtitles',
240 help='lists all available subtitles for the video', default=False)
241 subtitles.add_option('--sub-format',
242 action='store', dest='subtitlesformat', metavar='FORMAT',
243 help='subtitle format (default=srt) ([sbv/vtt] youtube only)', default='srt')
244 subtitles.add_option('--sub-lang', '--sub-langs', '--srt-lang',
245 action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
246 default=[], callback=_comma_separated_values_options_callback,
247 help='languages of the subtitles to download (optional) separated by commas, use IETF language tags like \'en,pt\'')
249 downloader.add_option('-r', '--rate-limit',
250 dest='ratelimit', metavar='LIMIT', help='maximum download rate in bytes per second (e.g. 50K or 4.2M)')
251 downloader.add_option('-R', '--retries',
252 dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
253 downloader.add_option('--buffer-size',
254 dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16K) (default is %default)', default="1024")
255 downloader.add_option('--no-resize-buffer',
256 action='store_true', dest='noresizebuffer',
257 help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
258 downloader.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
260 workarounds.add_option(
261 '--encoding', dest='encoding', metavar='ENCODING',
262 help='Force the specified encoding (experimental)')
263 workarounds.add_option(
264 '--no-check-certificate', action='store_true',
265 dest='no_check_certificate', default=False,
266 help='Suppress HTTPS certificate validation.')
267 workarounds.add_option(
268 '--prefer-insecure', '--prefer-unsecure', action='store_true', dest='prefer_insecure',
269 help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
270 workarounds.add_option(
271 '--user-agent', metavar='UA',
272 dest='user_agent', help='specify a custom user agent')
273 workarounds.add_option(
274 '--referer', metavar='REF',
275 dest='referer', default=None,
276 help='specify a custom referer, use if the video access is restricted to one domain',
278 workarounds.add_option(
279 '--add-header', metavar='FIELD:VALUE',
280 dest='headers', action='append',
281 help='specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
283 workarounds.add_option(
284 '--bidi-workaround', dest='bidi_workaround', action='store_true',
285 help=u'Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
287 verbosity.add_option('-q', '--quiet',
288 action='store_true', dest='quiet', help='activates quiet mode', default=False)
289 verbosity.add_option(
291 dest='no_warnings', action='store_true', default=False,
292 help='Ignore warnings')
293 verbosity.add_option('-s', '--simulate',
294 action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
295 verbosity.add_option('--skip-download',
296 action='store_true', dest='skip_download', help='do not download the video', default=False)
297 verbosity.add_option('-g', '--get-url',
298 action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
299 verbosity.add_option('-e', '--get-title',
300 action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
301 verbosity.add_option('--get-id',
302 action='store_true', dest='getid', help='simulate, quiet but print id', default=False)
303 verbosity.add_option('--get-thumbnail',
304 action='store_true', dest='getthumbnail',
305 help='simulate, quiet but print thumbnail URL', default=False)
306 verbosity.add_option('--get-description',
307 action='store_true', dest='getdescription',
308 help='simulate, quiet but print video description', default=False)
309 verbosity.add_option('--get-duration',
310 action='store_true', dest='getduration',
311 help='simulate, quiet but print video length', default=False)
312 verbosity.add_option('--get-filename',
313 action='store_true', dest='getfilename',
314 help='simulate, quiet but print output filename', default=False)
315 verbosity.add_option('--get-format',
316 action='store_true', dest='getformat',
317 help='simulate, quiet but print output format', default=False)
318 verbosity.add_option('-j', '--dump-json',
319 action='store_true', dest='dumpjson',
320 help='simulate, quiet but print JSON information. See --output for a description of available keys.', default=False)
321 verbosity.add_option('--newline',
322 action='store_true', dest='progress_with_newline', help='output progress bar as new lines', default=False)
323 verbosity.add_option('--no-progress',
324 action='store_true', dest='noprogress', help='do not print progress bar', default=False)
325 verbosity.add_option('--console-title',
326 action='store_true', dest='consoletitle',
327 help='display progress in console titlebar', default=False)
328 verbosity.add_option('-v', '--verbose',
329 action='store_true', dest='verbose', help='print various debugging information', default=False)
330 verbosity.add_option('--dump-intermediate-pages',
331 action='store_true', dest='dump_intermediate_pages', default=False,
332 help='print downloaded pages to debug problems (very verbose)')
333 verbosity.add_option('--write-pages',
334 action='store_true', dest='write_pages', default=False,
335 help='Write downloaded intermediary pages to files in the current directory to debug problems')
336 verbosity.add_option('--youtube-print-sig-code',
337 action='store_true', dest='youtube_print_sig_code', default=False,
338 help=optparse.SUPPRESS_HELP)
339 verbosity.add_option('--print-traffic',
340 dest='debug_printtraffic', action='store_true', default=False,
341 help='Display sent and read HTTP traffic')
344 filesystem.add_option('-a', '--batch-file',
345 dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
346 filesystem.add_option('--id',
347 action='store_true', dest='useid', help='use only video ID in file name', default=False)
348 filesystem.add_option('-A', '--auto-number',
349 action='store_true', dest='autonumber',
350 help='number downloaded files starting from 00000', default=False)
351 filesystem.add_option('-o', '--output',
352 dest='outtmpl', metavar='TEMPLATE',
353 help=('output filename template. Use %(title)s to get the title, '
354 '%(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, '
355 '%(autonumber)s to get an automatically incremented number, '
356 '%(ext)s for the filename extension, '
357 '%(format)s for the format description (like "22 - 1280x720" or "HD"), '
358 '%(format_id)s for the unique id of the format (like Youtube\'s itags: "137"), '
359 '%(upload_date)s for the upload date (YYYYMMDD), '
360 '%(extractor)s for the provider (youtube, metacafe, etc), '
361 '%(id)s for the video id, %(playlist)s for the playlist the video is in, '
362 '%(playlist_index)s for the position in the playlist and %% for a literal percent. '
363 '%(height)s and %(width)s for the width and height of the video format. '
364 '%(resolution)s for a textual description of the resolution of the video format. '
365 'Use - to output to stdout. Can also be used to download to a different directory, '
366 'for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .'))
367 filesystem.add_option('--autonumber-size',
368 dest='autonumber_size', metavar='NUMBER',
369 help='Specifies the number of digits in %(autonumber)s when it is present in output filename template or --auto-number option is given')
370 filesystem.add_option('--restrict-filenames',
371 action='store_true', dest='restrictfilenames',
372 help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
373 filesystem.add_option('-t', '--title',
374 action='store_true', dest='usetitle', help='[deprecated] use title in file name (default)', default=False)
375 filesystem.add_option('-l', '--literal',
376 action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
377 filesystem.add_option('-w', '--no-overwrites',
378 action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
379 filesystem.add_option('-c', '--continue',
380 action='store_true', dest='continue_dl', help='force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.', default=True)
381 filesystem.add_option('--no-continue',
382 action='store_false', dest='continue_dl',
383 help='do not resume partially downloaded files (restart from beginning)')
384 filesystem.add_option('--no-part',
385 action='store_true', dest='nopart', help='do not use .part files', default=False)
386 filesystem.add_option('--no-mtime',
387 action='store_false', dest='updatetime',
388 help='do not use the Last-modified header to set the file modification time', default=True)
389 filesystem.add_option('--write-description',
390 action='store_true', dest='writedescription',
391 help='write video description to a .description file', default=False)
392 filesystem.add_option('--write-info-json',
393 action='store_true', dest='writeinfojson',
394 help='write video metadata to a .info.json file', default=False)
395 filesystem.add_option('--write-annotations',
396 action='store_true', dest='writeannotations',
397 help='write video annotations to a .annotation file', default=False)
398 filesystem.add_option('--write-thumbnail',
399 action='store_true', dest='writethumbnail',
400 help='write thumbnail image to disk', default=False)
401 filesystem.add_option('--load-info',
402 dest='load_info_filename', metavar='FILE',
403 help='json file containing the video information (created with the "--write-json" option)')
404 filesystem.add_option('--cookies',
405 dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
406 filesystem.add_option(
407 '--cache-dir', dest='cachedir', default=None, metavar='DIR',
408 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.')
409 filesystem.add_option(
410 '--no-cache-dir', action='store_const', const=False, dest='cachedir',
411 help='Disable filesystem caching')
412 filesystem.add_option(
413 '--rm-cache-dir', action='store_true', dest='rm_cachedir',
414 help='Delete all filesystem cache files')
417 postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
418 help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
419 postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
420 help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
421 postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
422 help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
423 postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
424 help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv)')
425 postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
426 help='keeps the video file on disk after the post-processing; the video is erased by default')
427 postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
428 help='do not overwrite post-processed files; the post-processed files are overwritten by default')
429 postproc.add_option('--embed-subs', action='store_true', dest='embedsubtitles', default=False,
430 help='embed subtitles in the video (only for mp4 videos)')
431 postproc.add_option('--embed-thumbnail', action='store_true', dest='embedthumbnail', default=False,
432 help='embed thumbnail in the audio as cover art')
433 postproc.add_option('--add-metadata', action='store_true', dest='addmetadata', default=False,
434 help='write metadata to the video file')
435 postproc.add_option('--xattrs', action='store_true', dest='xattrs', default=False,
436 help='write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
437 postproc.add_option('--prefer-avconv', action='store_false', dest='prefer_ffmpeg',
438 help='Prefer avconv over ffmpeg for running the postprocessors (default)')
439 postproc.add_option('--prefer-ffmpeg', action='store_true', dest='prefer_ffmpeg',
440 help='Prefer ffmpeg over avconv for running the postprocessors')
442 '--exec', metavar='CMD', dest='exec_cmd',
443 help='Execute a command on the file after downloading, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'' )
445 parser.add_option_group(general)
446 parser.add_option_group(selection)
447 parser.add_option_group(downloader)
448 parser.add_option_group(filesystem)
449 parser.add_option_group(verbosity)
450 parser.add_option_group(workarounds)
451 parser.add_option_group(video_format)
452 parser.add_option_group(subtitles)
453 parser.add_option_group(authentication)
454 parser.add_option_group(postproc)
456 if overrideArguments is not None:
457 opts, args = parser.parse_args(overrideArguments)
459 write_string(u'[debug] Override config: ' + repr(overrideArguments) + '\n')
461 commandLineConf = sys.argv[1:]
462 if '--ignore-config' in commandLineConf:
466 systemConf = _readOptions('/etc/youtube-dl.conf')
467 if '--ignore-config' in systemConf:
470 userConf = _readUserConf()
471 argv = systemConf + userConf + commandLineConf
473 opts, args = parser.parse_args(argv)
475 write_string(u'[debug] System config: ' + repr(_hide_login_info(systemConf)) + '\n')
476 write_string(u'[debug] User config: ' + repr(_hide_login_info(userConf)) + '\n')
477 write_string(u'[debug] Command-line args: ' + repr(_hide_login_info(commandLineConf)) + '\n')
479 return parser, opts, args