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