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