logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

options.py (42565B)


  1. from __future__ import unicode_literals
  2. import os.path
  3. import optparse
  4. import re
  5. import sys
  6. from .downloader.external import list_external_downloaders
  7. from .compat import (
  8. compat_expanduser,
  9. compat_get_terminal_size,
  10. compat_getenv,
  11. compat_kwargs,
  12. compat_shlex_split,
  13. )
  14. from .utils import (
  15. preferredencoding,
  16. write_string,
  17. )
  18. from .version import __version__
  19. def _hide_login_info(opts):
  20. PRIVATE_OPTS = set(['-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'])
  21. eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
  22. def _scrub_eq(o):
  23. m = eqre.match(o)
  24. if m:
  25. return m.group('key') + '=PRIVATE'
  26. else:
  27. return o
  28. opts = list(map(_scrub_eq, opts))
  29. for idx, opt in enumerate(opts):
  30. if opt in PRIVATE_OPTS and idx + 1 < len(opts):
  31. opts[idx + 1] = 'PRIVATE'
  32. return opts
  33. def parseOpts(overrideArguments=None):
  34. def _readOptions(filename_bytes, default=[]):
  35. try:
  36. optionf = open(filename_bytes)
  37. except IOError:
  38. return default # silently skip if file is not present
  39. try:
  40. # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
  41. contents = optionf.read()
  42. if sys.version_info < (3,):
  43. contents = contents.decode(preferredencoding())
  44. res = compat_shlex_split(contents, comments=True)
  45. finally:
  46. optionf.close()
  47. return res
  48. def _readUserConf():
  49. xdg_config_home = compat_getenv('XDG_CONFIG_HOME')
  50. if xdg_config_home:
  51. userConfFile = os.path.join(xdg_config_home, 'youtube-dl', 'config')
  52. if not os.path.isfile(userConfFile):
  53. userConfFile = os.path.join(xdg_config_home, 'youtube-dl.conf')
  54. else:
  55. userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl', 'config')
  56. if not os.path.isfile(userConfFile):
  57. userConfFile = os.path.join(compat_expanduser('~'), '.config', 'youtube-dl.conf')
  58. userConf = _readOptions(userConfFile, None)
  59. if userConf is None:
  60. appdata_dir = compat_getenv('appdata')
  61. if appdata_dir:
  62. userConf = _readOptions(
  63. os.path.join(appdata_dir, 'youtube-dl', 'config'),
  64. default=None)
  65. if userConf is None:
  66. userConf = _readOptions(
  67. os.path.join(appdata_dir, 'youtube-dl', 'config.txt'),
  68. default=None)
  69. if userConf is None:
  70. userConf = _readOptions(
  71. os.path.join(compat_expanduser('~'), 'youtube-dl.conf'),
  72. default=None)
  73. if userConf is None:
  74. userConf = _readOptions(
  75. os.path.join(compat_expanduser('~'), 'youtube-dl.conf.txt'),
  76. default=None)
  77. if userConf is None:
  78. userConf = []
  79. return userConf
  80. def _format_option_string(option):
  81. ''' ('-o', '--option') -> -o, --format METAVAR'''
  82. opts = []
  83. if option._short_opts:
  84. opts.append(option._short_opts[0])
  85. if option._long_opts:
  86. opts.append(option._long_opts[0])
  87. if len(opts) > 1:
  88. opts.insert(1, ', ')
  89. if option.takes_value():
  90. opts.append(' %s' % option.metavar)
  91. return ''.join(opts)
  92. def _comma_separated_values_options_callback(option, opt_str, value, parser):
  93. setattr(parser.values, option.dest, value.split(','))
  94. # No need to wrap help messages if we're on a wide console
  95. columns = compat_get_terminal_size().columns
  96. max_width = columns if columns else 80
  97. max_help_position = 80
  98. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  99. fmt.format_option_strings = _format_option_string
  100. kw = {
  101. 'version': __version__,
  102. 'formatter': fmt,
  103. 'usage': '%prog [OPTIONS] URL [URL...]',
  104. 'conflict_handler': 'resolve',
  105. }
  106. parser = optparse.OptionParser(**compat_kwargs(kw))
  107. general = optparse.OptionGroup(parser, 'General Options')
  108. general.add_option(
  109. '-h', '--help',
  110. action='help',
  111. help='Print this help text and exit')
  112. general.add_option(
  113. '--version',
  114. action='version',
  115. help='Print program version and exit')
  116. general.add_option(
  117. '-U', '--update',
  118. action='store_true', dest='update_self',
  119. help='Update this program to latest version. Make sure that you have sufficient permissions (run with sudo if needed)')
  120. general.add_option(
  121. '-i', '--ignore-errors',
  122. action='store_true', dest='ignoreerrors', default=False,
  123. help='Continue on download errors, for example to skip unavailable videos in a playlist')
  124. general.add_option(
  125. '--abort-on-error',
  126. action='store_false', dest='ignoreerrors',
  127. help='Abort downloading of further videos (in the playlist or the command line) if an error occurs')
  128. general.add_option(
  129. '--dump-user-agent',
  130. action='store_true', dest='dump_user_agent', default=False,
  131. help='Display the current browser identification')
  132. general.add_option(
  133. '--list-extractors',
  134. action='store_true', dest='list_extractors', default=False,
  135. help='List all supported extractors')
  136. general.add_option(
  137. '--extractor-descriptions',
  138. action='store_true', dest='list_extractor_descriptions', default=False,
  139. help='Output descriptions of all supported extractors')
  140. general.add_option(
  141. '--force-generic-extractor',
  142. action='store_true', dest='force_generic_extractor', default=False,
  143. help='Force extraction to use the generic extractor')
  144. general.add_option(
  145. '--default-search',
  146. dest='default_search', metavar='PREFIX',
  147. 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.')
  148. general.add_option(
  149. '--ignore-config',
  150. action='store_true',
  151. help='Do not read configuration files. '
  152. 'When given in the global configuration file /etc/youtube-dl.conf: '
  153. 'Do not read the user configuration in ~/.config/youtube-dl/config '
  154. '(%APPDATA%/youtube-dl/config.txt on Windows)')
  155. general.add_option(
  156. '--config-location',
  157. dest='config_location', metavar='PATH',
  158. help='Location of the configuration file; either the path to the config or its containing directory.')
  159. general.add_option(
  160. '--flat-playlist',
  161. action='store_const', dest='extract_flat', const='in_playlist',
  162. default=False,
  163. help='Do not extract the videos of a playlist, only list them.')
  164. general.add_option(
  165. '--mark-watched',
  166. action='store_true', dest='mark_watched', default=False,
  167. help='Mark videos watched (YouTube only)')
  168. general.add_option(
  169. '--no-mark-watched',
  170. action='store_false', dest='mark_watched', default=False,
  171. help='Do not mark videos watched (YouTube only)')
  172. general.add_option(
  173. '--no-color', '--no-colors',
  174. action='store_true', dest='no_color',
  175. default=False,
  176. help='Do not emit color codes in output')
  177. network = optparse.OptionGroup(parser, 'Network Options')
  178. network.add_option(
  179. '--proxy', dest='proxy',
  180. default=None, metavar='URL',
  181. help='Use the specified HTTP/HTTPS/SOCKS proxy. To enable '
  182. 'SOCKS proxy, specify a proper scheme. For example '
  183. 'socks5://127.0.0.1:1080/. Pass in an empty string (--proxy "") '
  184. 'for direct connection')
  185. network.add_option(
  186. '--socket-timeout',
  187. dest='socket_timeout', type=float, default=None, metavar='SECONDS',
  188. help='Time to wait before giving up, in seconds')
  189. network.add_option(
  190. '--source-address',
  191. metavar='IP', dest='source_address', default=None,
  192. help='Client-side IP address to bind to',
  193. )
  194. network.add_option(
  195. '-4', '--force-ipv4',
  196. action='store_const', const='0.0.0.0', dest='source_address',
  197. help='Make all connections via IPv4',
  198. )
  199. network.add_option(
  200. '-6', '--force-ipv6',
  201. action='store_const', const='::', dest='source_address',
  202. help='Make all connections via IPv6',
  203. )
  204. geo = optparse.OptionGroup(parser, 'Geo Restriction')
  205. geo.add_option(
  206. '--geo-verification-proxy',
  207. dest='geo_verification_proxy', default=None, metavar='URL',
  208. help='Use this proxy to verify the IP address for some geo-restricted sites. '
  209. 'The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading.')
  210. geo.add_option(
  211. '--cn-verification-proxy',
  212. dest='cn_verification_proxy', default=None, metavar='URL',
  213. help=optparse.SUPPRESS_HELP)
  214. geo.add_option(
  215. '--geo-bypass',
  216. action='store_true', dest='geo_bypass', default=True,
  217. help='Bypass geographic restriction via faking X-Forwarded-For HTTP header')
  218. geo.add_option(
  219. '--no-geo-bypass',
  220. action='store_false', dest='geo_bypass', default=True,
  221. help='Do not bypass geographic restriction via faking X-Forwarded-For HTTP header')
  222. geo.add_option(
  223. '--geo-bypass-country', metavar='CODE',
  224. dest='geo_bypass_country', default=None,
  225. help='Force bypass geographic restriction with explicitly provided two-letter ISO 3166-2 country code')
  226. geo.add_option(
  227. '--geo-bypass-ip-block', metavar='IP_BLOCK',
  228. dest='geo_bypass_ip_block', default=None,
  229. help='Force bypass geographic restriction with explicitly provided IP block in CIDR notation')
  230. selection = optparse.OptionGroup(parser, 'Video Selection')
  231. selection.add_option(
  232. '--playlist-start',
  233. dest='playliststart', metavar='NUMBER', default=1, type=int,
  234. help='Playlist video to start at (default is %default)')
  235. selection.add_option(
  236. '--playlist-end',
  237. dest='playlistend', metavar='NUMBER', default=None, type=int,
  238. help='Playlist video to end at (default is last)')
  239. selection.add_option(
  240. '--playlist-items',
  241. dest='playlist_items', metavar='ITEM_SPEC', default=None,
  242. help='Playlist video items to download. Specify indices of the videos in the playlist separated by commas like: "--playlist-items 1,2,5,8" if you want to download videos indexed 1, 2, 5, 8 in the playlist. You can specify range: "--playlist-items 1-3,7,10-13", it will download the videos at index 1, 2, 3, 7, 10, 11, 12 and 13.')
  243. selection.add_option(
  244. '--match-title',
  245. dest='matchtitle', metavar='REGEX',
  246. help='Download only matching titles (case-insensitive regex or alphanumeric sub-string)')
  247. selection.add_option(
  248. '--reject-title',
  249. dest='rejecttitle', metavar='REGEX',
  250. help='Skip download for matching titles (case-insensitive regex or alphanumeric sub-string)')
  251. selection.add_option(
  252. '--max-downloads',
  253. dest='max_downloads', metavar='NUMBER', type=int, default=None,
  254. help='Abort after downloading NUMBER files')
  255. selection.add_option(
  256. '--min-filesize',
  257. metavar='SIZE', dest='min_filesize', default=None,
  258. help='Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)')
  259. selection.add_option(
  260. '--max-filesize',
  261. metavar='SIZE', dest='max_filesize', default=None,
  262. help='Do not download any videos larger than SIZE (e.g. 50k or 44.6m)')
  263. selection.add_option(
  264. '--date',
  265. metavar='DATE', dest='date', default=None,
  266. help='Download only videos uploaded in this date')
  267. selection.add_option(
  268. '--datebefore',
  269. metavar='DATE', dest='datebefore', default=None,
  270. help='Download only videos uploaded on or before this date (i.e. inclusive)')
  271. selection.add_option(
  272. '--dateafter',
  273. metavar='DATE', dest='dateafter', default=None,
  274. help='Download only videos uploaded on or after this date (i.e. inclusive)')
  275. selection.add_option(
  276. '--min-views',
  277. metavar='COUNT', dest='min_views', default=None, type=int,
  278. help='Do not download any videos with less than COUNT views')
  279. selection.add_option(
  280. '--max-views',
  281. metavar='COUNT', dest='max_views', default=None, type=int,
  282. help='Do not download any videos with more than COUNT views')
  283. selection.add_option(
  284. '--match-filter',
  285. metavar='FILTER', dest='match_filter', default=None,
  286. help=(
  287. 'Generic video filter. '
  288. 'Specify any key (see the "OUTPUT TEMPLATE" for a list of available keys) to '
  289. 'match if the key is present, '
  290. '!key to check if the key is not present, '
  291. 'key > NUMBER (like "comment_count > 12", also works with '
  292. '>=, <, <=, !=, =) to compare against a number, '
  293. 'key = \'LITERAL\' (like "uploader = \'Mike Smith\'", also works with !=) '
  294. 'to match against a string literal '
  295. 'and & to require multiple matches. '
  296. 'Values which are not known are excluded unless you '
  297. 'put a question mark (?) after the operator. '
  298. 'For example, to only match videos that have been liked more than '
  299. '100 times and disliked less than 50 times (or the dislike '
  300. 'functionality is not available at the given service), but who '
  301. 'also have a description, use --match-filter '
  302. '"like_count > 100 & dislike_count <? 50 & description" .'
  303. ))
  304. selection.add_option(
  305. '--no-playlist',
  306. action='store_true', dest='noplaylist', default=False,
  307. help='Download only the video, if the URL refers to a video and a playlist.')
  308. selection.add_option(
  309. '--yes-playlist',
  310. action='store_false', dest='noplaylist', default=False,
  311. help='Download the playlist, if the URL refers to a video and a playlist.')
  312. selection.add_option(
  313. '--age-limit',
  314. metavar='YEARS', dest='age_limit', default=None, type=int,
  315. help='Download only videos suitable for the given age')
  316. selection.add_option(
  317. '--download-archive', metavar='FILE',
  318. dest='download_archive',
  319. help='Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it.')
  320. selection.add_option(
  321. '--include-ads',
  322. dest='include_ads', action='store_true',
  323. help='Download advertisements as well (experimental)')
  324. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  325. authentication.add_option(
  326. '-u', '--username',
  327. dest='username', metavar='USERNAME',
  328. help='Login with this account ID')
  329. authentication.add_option(
  330. '-p', '--password',
  331. dest='password', metavar='PASSWORD',
  332. help='Account password. If this option is left out, youtube-dl will ask interactively.')
  333. authentication.add_option(
  334. '-2', '--twofactor',
  335. dest='twofactor', metavar='TWOFACTOR',
  336. help='Two-factor authentication code')
  337. authentication.add_option(
  338. '-n', '--netrc',
  339. action='store_true', dest='usenetrc', default=False,
  340. help='Use .netrc authentication data')
  341. authentication.add_option(
  342. '--video-password',
  343. dest='videopassword', metavar='PASSWORD',
  344. help='Video password (vimeo, youku)')
  345. adobe_pass = optparse.OptionGroup(parser, 'Adobe Pass Options')
  346. adobe_pass.add_option(
  347. '--ap-mso',
  348. dest='ap_mso', metavar='MSO',
  349. help='Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs')
  350. adobe_pass.add_option(
  351. '--ap-username',
  352. dest='ap_username', metavar='USERNAME',
  353. help='Multiple-system operator account login')
  354. adobe_pass.add_option(
  355. '--ap-password',
  356. dest='ap_password', metavar='PASSWORD',
  357. help='Multiple-system operator account password. If this option is left out, youtube-dl will ask interactively.')
  358. adobe_pass.add_option(
  359. '--ap-list-mso',
  360. action='store_true', dest='ap_list_mso', default=False,
  361. help='List all supported multiple-system operators')
  362. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  363. video_format.add_option(
  364. '-f', '--format',
  365. action='store', dest='format', metavar='FORMAT', default=None,
  366. help='Video format code, see the "FORMAT SELECTION" for all the info')
  367. video_format.add_option(
  368. '--all-formats',
  369. action='store_const', dest='format', const='all',
  370. help='Download all available video formats')
  371. video_format.add_option(
  372. '--prefer-free-formats',
  373. action='store_true', dest='prefer_free_formats', default=False,
  374. help='Prefer free video formats unless a specific one is requested')
  375. video_format.add_option(
  376. '-F', '--list-formats',
  377. action='store_true', dest='listformats',
  378. help='List all available formats of requested videos')
  379. video_format.add_option(
  380. '--youtube-include-dash-manifest',
  381. action='store_true', dest='youtube_include_dash_manifest', default=True,
  382. help=optparse.SUPPRESS_HELP)
  383. video_format.add_option(
  384. '--youtube-skip-dash-manifest',
  385. action='store_false', dest='youtube_include_dash_manifest',
  386. help='Do not download the DASH manifests and related data on YouTube videos')
  387. video_format.add_option(
  388. '--merge-output-format',
  389. action='store', dest='merge_output_format', metavar='FORMAT', default=None,
  390. help=(
  391. 'If a merge is required (e.g. bestvideo+bestaudio), '
  392. 'output to given container format. One of mkv, mp4, ogg, webm, flv. '
  393. 'Ignored if no merge is required'))
  394. subtitles = optparse.OptionGroup(parser, 'Subtitle Options')
  395. subtitles.add_option(
  396. '--write-sub', '--write-srt',
  397. action='store_true', dest='writesubtitles', default=False,
  398. help='Write subtitle file')
  399. subtitles.add_option(
  400. '--write-auto-sub', '--write-automatic-sub',
  401. action='store_true', dest='writeautomaticsub', default=False,
  402. help='Write automatically generated subtitle file (YouTube only)')
  403. subtitles.add_option(
  404. '--all-subs',
  405. action='store_true', dest='allsubtitles', default=False,
  406. help='Download all the available subtitles of the video')
  407. subtitles.add_option(
  408. '--list-subs',
  409. action='store_true', dest='listsubtitles', default=False,
  410. help='List all available subtitles for the video')
  411. subtitles.add_option(
  412. '--sub-format',
  413. action='store', dest='subtitlesformat', metavar='FORMAT', default='best',
  414. help='Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"')
  415. subtitles.add_option(
  416. '--sub-lang', '--sub-langs', '--srt-lang',
  417. action='callback', dest='subtitleslangs', metavar='LANGS', type='str',
  418. default=[], callback=_comma_separated_values_options_callback,
  419. help='Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags')
  420. downloader = optparse.OptionGroup(parser, 'Download Options')
  421. downloader.add_option(
  422. '-r', '--limit-rate', '--rate-limit',
  423. dest='ratelimit', metavar='RATE',
  424. help='Maximum download rate in bytes per second (e.g. 50K or 4.2M)')
  425. downloader.add_option(
  426. '-R', '--retries',
  427. dest='retries', metavar='RETRIES', default=10,
  428. help='Number of retries (default is %default), or "infinite".')
  429. downloader.add_option(
  430. '--fragment-retries',
  431. dest='fragment_retries', metavar='RETRIES', default=10,
  432. help='Number of retries for a fragment (default is %default), or "infinite" (DASH, hlsnative and ISM)')
  433. downloader.add_option(
  434. '--skip-unavailable-fragments',
  435. action='store_true', dest='skip_unavailable_fragments', default=True,
  436. help='Skip unavailable fragments (DASH, hlsnative and ISM)')
  437. downloader.add_option(
  438. '--abort-on-unavailable-fragment',
  439. action='store_false', dest='skip_unavailable_fragments',
  440. help='Abort downloading when some fragment is not available')
  441. downloader.add_option(
  442. '--keep-fragments',
  443. action='store_true', dest='keep_fragments', default=False,
  444. help='Keep downloaded fragments on disk after downloading is finished; fragments are erased by default')
  445. downloader.add_option(
  446. '--buffer-size',
  447. dest='buffersize', metavar='SIZE', default='1024',
  448. help='Size of download buffer (e.g. 1024 or 16K) (default is %default)')
  449. downloader.add_option(
  450. '--no-resize-buffer',
  451. action='store_true', dest='noresizebuffer', default=False,
  452. help='Do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.')
  453. downloader.add_option(
  454. '--http-chunk-size',
  455. dest='http_chunk_size', metavar='SIZE', default=None,
  456. help='Size of a chunk for chunk-based HTTP downloading (e.g. 10485760 or 10M) (default is disabled). '
  457. 'May be useful for bypassing bandwidth throttling imposed by a webserver (experimental)')
  458. downloader.add_option(
  459. '--test',
  460. action='store_true', dest='test', default=False,
  461. help=optparse.SUPPRESS_HELP)
  462. downloader.add_option(
  463. '--playlist-reverse',
  464. action='store_true',
  465. help='Download playlist videos in reverse order')
  466. downloader.add_option(
  467. '--playlist-random',
  468. action='store_true',
  469. help='Download playlist videos in random order')
  470. downloader.add_option(
  471. '--xattr-set-filesize',
  472. dest='xattr_set_filesize', action='store_true',
  473. help='Set file xattribute ytdl.filesize with expected file size')
  474. downloader.add_option(
  475. '--hls-prefer-native',
  476. dest='hls_prefer_native', action='store_true', default=None,
  477. help='Use the native HLS downloader instead of ffmpeg')
  478. downloader.add_option(
  479. '--hls-prefer-ffmpeg',
  480. dest='hls_prefer_native', action='store_false', default=None,
  481. help='Use ffmpeg instead of the native HLS downloader')
  482. downloader.add_option(
  483. '--hls-use-mpegts',
  484. dest='hls_use_mpegts', action='store_true',
  485. help='Use the mpegts container for HLS videos, allowing to play the '
  486. 'video while downloading (some players may not be able to play it)')
  487. downloader.add_option(
  488. '--external-downloader',
  489. dest='external_downloader', metavar='COMMAND',
  490. help='Use the specified external downloader. '
  491. 'Currently supports %s' % ','.join(list_external_downloaders()))
  492. downloader.add_option(
  493. '--external-downloader-args',
  494. dest='external_downloader_args', metavar='ARGS',
  495. help='Give these arguments to the external downloader')
  496. workarounds = optparse.OptionGroup(parser, 'Workarounds')
  497. workarounds.add_option(
  498. '--encoding',
  499. dest='encoding', metavar='ENCODING',
  500. help='Force the specified encoding (experimental)')
  501. workarounds.add_option(
  502. '--no-check-certificate',
  503. action='store_true', dest='no_check_certificate', default=False,
  504. help='Suppress HTTPS certificate validation')
  505. workarounds.add_option(
  506. '--prefer-insecure',
  507. '--prefer-unsecure', action='store_true', dest='prefer_insecure',
  508. help='Use an unencrypted connection to retrieve information about the video. (Currently supported only for YouTube)')
  509. workarounds.add_option(
  510. '--user-agent',
  511. metavar='UA', dest='user_agent',
  512. help='Specify a custom user agent')
  513. workarounds.add_option(
  514. '--referer',
  515. metavar='URL', dest='referer', default=None,
  516. help='Specify a custom referer, use if the video access is restricted to one domain',
  517. )
  518. workarounds.add_option(
  519. '--add-header',
  520. metavar='FIELD:VALUE', dest='headers', action='append',
  521. help='Specify a custom HTTP header and its value, separated by a colon \':\'. You can use this option multiple times',
  522. )
  523. workarounds.add_option(
  524. '--bidi-workaround',
  525. dest='bidi_workaround', action='store_true',
  526. help='Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH')
  527. workarounds.add_option(
  528. '--sleep-interval', '--min-sleep-interval', metavar='SECONDS',
  529. dest='sleep_interval', type=float,
  530. help=(
  531. 'Number of seconds to sleep before each download when used alone '
  532. 'or a lower bound of a range for randomized sleep before each download '
  533. '(minimum possible number of seconds to sleep) when used along with '
  534. '--max-sleep-interval.'))
  535. workarounds.add_option(
  536. '--max-sleep-interval', metavar='SECONDS',
  537. dest='max_sleep_interval', type=float,
  538. help=(
  539. 'Upper bound of a range for randomized sleep before each download '
  540. '(maximum possible number of seconds to sleep). Must only be used '
  541. 'along with --min-sleep-interval.'))
  542. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  543. verbosity.add_option(
  544. '-q', '--quiet',
  545. action='store_true', dest='quiet', default=False,
  546. help='Activate quiet mode')
  547. verbosity.add_option(
  548. '--no-warnings',
  549. dest='no_warnings', action='store_true', default=False,
  550. help='Ignore warnings')
  551. verbosity.add_option(
  552. '-s', '--simulate',
  553. action='store_true', dest='simulate', default=False,
  554. help='Do not download the video and do not write anything to disk')
  555. verbosity.add_option(
  556. '--skip-download',
  557. action='store_true', dest='skip_download', default=False,
  558. help='Do not download the video')
  559. verbosity.add_option(
  560. '-g', '--get-url',
  561. action='store_true', dest='geturl', default=False,
  562. help='Simulate, quiet but print URL')
  563. verbosity.add_option(
  564. '-e', '--get-title',
  565. action='store_true', dest='gettitle', default=False,
  566. help='Simulate, quiet but print title')
  567. verbosity.add_option(
  568. '--get-id',
  569. action='store_true', dest='getid', default=False,
  570. help='Simulate, quiet but print id')
  571. verbosity.add_option(
  572. '--get-thumbnail',
  573. action='store_true', dest='getthumbnail', default=False,
  574. help='Simulate, quiet but print thumbnail URL')
  575. verbosity.add_option(
  576. '--get-description',
  577. action='store_true', dest='getdescription', default=False,
  578. help='Simulate, quiet but print video description')
  579. verbosity.add_option(
  580. '--get-duration',
  581. action='store_true', dest='getduration', default=False,
  582. help='Simulate, quiet but print video length')
  583. verbosity.add_option(
  584. '--get-filename',
  585. action='store_true', dest='getfilename', default=False,
  586. help='Simulate, quiet but print output filename')
  587. verbosity.add_option(
  588. '--get-format',
  589. action='store_true', dest='getformat', default=False,
  590. help='Simulate, quiet but print output format')
  591. verbosity.add_option(
  592. '-j', '--dump-json',
  593. action='store_true', dest='dumpjson', default=False,
  594. help='Simulate, quiet but print JSON information. See the "OUTPUT TEMPLATE" for a description of available keys.')
  595. verbosity.add_option(
  596. '-J', '--dump-single-json',
  597. action='store_true', dest='dump_single_json', default=False,
  598. help='Simulate, quiet but print JSON information for each command-line argument. If the URL refers to a playlist, dump the whole playlist information in a single line.')
  599. verbosity.add_option(
  600. '--print-json',
  601. action='store_true', dest='print_json', default=False,
  602. help='Be quiet and print the video information as JSON (video is still being downloaded).',
  603. )
  604. verbosity.add_option(
  605. '--newline',
  606. action='store_true', dest='progress_with_newline', default=False,
  607. help='Output progress bar as new lines')
  608. verbosity.add_option(
  609. '--no-progress',
  610. action='store_true', dest='noprogress', default=False,
  611. help='Do not print progress bar')
  612. verbosity.add_option(
  613. '--console-title',
  614. action='store_true', dest='consoletitle', default=False,
  615. help='Display progress in console titlebar')
  616. verbosity.add_option(
  617. '-v', '--verbose',
  618. action='store_true', dest='verbose', default=False,
  619. help='Print various debugging information')
  620. verbosity.add_option(
  621. '--dump-pages', '--dump-intermediate-pages',
  622. action='store_true', dest='dump_intermediate_pages', default=False,
  623. help='Print downloaded pages encoded using base64 to debug problems (very verbose)')
  624. verbosity.add_option(
  625. '--write-pages',
  626. action='store_true', dest='write_pages', default=False,
  627. help='Write downloaded intermediary pages to files in the current directory to debug problems')
  628. verbosity.add_option(
  629. '--youtube-print-sig-code',
  630. action='store_true', dest='youtube_print_sig_code', default=False,
  631. help=optparse.SUPPRESS_HELP)
  632. verbosity.add_option(
  633. '--print-traffic', '--dump-headers',
  634. dest='debug_printtraffic', action='store_true', default=False,
  635. help='Display sent and read HTTP traffic')
  636. verbosity.add_option(
  637. '-C', '--call-home',
  638. dest='call_home', action='store_true', default=False,
  639. help='Contact the youtube-dl server for debugging')
  640. verbosity.add_option(
  641. '--no-call-home',
  642. dest='call_home', action='store_false', default=False,
  643. help='Do NOT contact the youtube-dl server for debugging')
  644. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  645. filesystem.add_option(
  646. '-a', '--batch-file',
  647. dest='batchfile', metavar='FILE',
  648. help="File containing URLs to download ('-' for stdin), one URL per line. "
  649. "Lines starting with '#', ';' or ']' are considered as comments and ignored.")
  650. filesystem.add_option(
  651. '--id', default=False,
  652. action='store_true', dest='useid', help='Use only video ID in file name')
  653. filesystem.add_option(
  654. '-o', '--output',
  655. dest='outtmpl', metavar='TEMPLATE',
  656. help=('Output filename template, see the "OUTPUT TEMPLATE" for all the info'))
  657. filesystem.add_option(
  658. '--output-na-placeholder',
  659. dest='outtmpl_na_placeholder', metavar='PLACEHOLDER', default='NA',
  660. help=('Placeholder value for unavailable meta fields in output filename template (default is "%default")'))
  661. filesystem.add_option(
  662. '--autonumber-size',
  663. dest='autonumber_size', metavar='NUMBER', type=int,
  664. help=optparse.SUPPRESS_HELP)
  665. filesystem.add_option(
  666. '--autonumber-start',
  667. dest='autonumber_start', metavar='NUMBER', default=1, type=int,
  668. help='Specify the start value for %(autonumber)s (default is %default)')
  669. filesystem.add_option(
  670. '--restrict-filenames',
  671. action='store_true', dest='restrictfilenames', default=False,
  672. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
  673. filesystem.add_option(
  674. '-A', '--auto-number',
  675. action='store_true', dest='autonumber', default=False,
  676. help=optparse.SUPPRESS_HELP)
  677. filesystem.add_option(
  678. '-t', '--title',
  679. action='store_true', dest='usetitle', default=False,
  680. help=optparse.SUPPRESS_HELP)
  681. filesystem.add_option(
  682. '-l', '--literal', default=False,
  683. action='store_true', dest='usetitle',
  684. help=optparse.SUPPRESS_HELP)
  685. filesystem.add_option(
  686. '-w', '--no-overwrites',
  687. action='store_true', dest='nooverwrites', default=False,
  688. help='Do not overwrite files')
  689. filesystem.add_option(
  690. '-c', '--continue',
  691. action='store_true', dest='continue_dl', default=True,
  692. help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
  693. filesystem.add_option(
  694. '--no-continue',
  695. action='store_false', dest='continue_dl',
  696. help='Do not resume partially downloaded files (restart from beginning)')
  697. filesystem.add_option(
  698. '--no-part',
  699. action='store_true', dest='nopart', default=False,
  700. help='Do not use .part files - write directly into output file')
  701. filesystem.add_option(
  702. '--no-mtime',
  703. action='store_false', dest='updatetime', default=True,
  704. help='Do not use the Last-modified header to set the file modification time')
  705. filesystem.add_option(
  706. '--write-description',
  707. action='store_true', dest='writedescription', default=False,
  708. help='Write video description to a .description file')
  709. filesystem.add_option(
  710. '--write-info-json',
  711. action='store_true', dest='writeinfojson', default=False,
  712. help='Write video metadata to a .info.json file')
  713. filesystem.add_option(
  714. '--write-annotations',
  715. action='store_true', dest='writeannotations', default=False,
  716. help='Write video annotations to a .annotations.xml file')
  717. filesystem.add_option(
  718. '--load-info-json', '--load-info',
  719. dest='load_info_filename', metavar='FILE',
  720. help='JSON file containing the video information (created with the "--write-info-json" option)')
  721. filesystem.add_option(
  722. '--cookies',
  723. dest='cookiefile', metavar='FILE',
  724. help='File to read cookies from and dump cookie jar in')
  725. filesystem.add_option(
  726. '--cache-dir', dest='cachedir', default=None, metavar='DIR',
  727. 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.')
  728. filesystem.add_option(
  729. '--no-cache-dir', action='store_const', const=False, dest='cachedir',
  730. help='Disable filesystem caching')
  731. filesystem.add_option(
  732. '--rm-cache-dir',
  733. action='store_true', dest='rm_cachedir',
  734. help='Delete all filesystem cache files')
  735. thumbnail = optparse.OptionGroup(parser, 'Thumbnail Options')
  736. thumbnail.add_option(
  737. '--write-thumbnail',
  738. action='store_true', dest='writethumbnail', default=False,
  739. help='Write thumbnail image to disk')
  740. thumbnail.add_option(
  741. '--write-all-thumbnails',
  742. action='store_true', dest='write_all_thumbnails', default=False,
  743. help='Write all thumbnail image formats to disk')
  744. thumbnail.add_option(
  745. '--list-thumbnails',
  746. action='store_true', dest='list_thumbnails', default=False,
  747. help='Simulate and list all available thumbnail formats')
  748. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  749. postproc.add_option(
  750. '-x', '--extract-audio',
  751. action='store_true', dest='extractaudio', default=False,
  752. help='Convert video files to audio-only files (requires ffmpeg/avconv and ffprobe/avprobe)')
  753. postproc.add_option(
  754. '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  755. help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
  756. postproc.add_option(
  757. '--audio-quality', metavar='QUALITY',
  758. dest='audioquality', default='5',
  759. help='Specify ffmpeg/avconv audio quality, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default %default)')
  760. postproc.add_option(
  761. '--recode-video',
  762. metavar='FORMAT', dest='recodevideo', default=None,
  763. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
  764. postproc.add_option(
  765. '--postprocessor-args',
  766. dest='postprocessor_args', metavar='ARGS',
  767. help='Give these arguments to the postprocessor (if postprocessing is required)')
  768. postproc.add_option(
  769. '-k', '--keep-video',
  770. action='store_true', dest='keepvideo', default=False,
  771. help='Keep the video file on disk after the post-processing; the video is erased by default')
  772. postproc.add_option(
  773. '--no-post-overwrites',
  774. action='store_true', dest='nopostoverwrites', default=False,
  775. help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
  776. postproc.add_option(
  777. '--embed-subs',
  778. action='store_true', dest='embedsubtitles', default=False,
  779. help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
  780. postproc.add_option(
  781. '--embed-thumbnail',
  782. action='store_true', dest='embedthumbnail', default=False,
  783. help='Embed thumbnail in the audio as cover art')
  784. postproc.add_option(
  785. '--add-metadata',
  786. action='store_true', dest='addmetadata', default=False,
  787. help='Write metadata to the video file')
  788. postproc.add_option(
  789. '--metadata-from-title',
  790. metavar='FORMAT', dest='metafromtitle',
  791. help='Parse additional metadata like song title / artist from the video title. '
  792. 'The format syntax is the same as --output. Regular expression with '
  793. 'named capture groups may also be used. '
  794. 'The parsed parameters replace existing values. '
  795. 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
  796. '"Coldplay - Paradise". '
  797. 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"')
  798. postproc.add_option(
  799. '--xattrs',
  800. action='store_true', dest='xattrs', default=False,
  801. help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  802. postproc.add_option(
  803. '--fixup',
  804. metavar='POLICY', dest='fixup', default='detect_or_warn',
  805. help='Automatically correct known faults of the file. '
  806. 'One of never (do nothing), warn (only emit a warning), '
  807. 'detect_or_warn (the default; fix file if we can, warn otherwise)')
  808. postproc.add_option(
  809. '--prefer-avconv',
  810. action='store_false', dest='prefer_ffmpeg',
  811. help='Prefer avconv over ffmpeg for running the postprocessors')
  812. postproc.add_option(
  813. '--prefer-ffmpeg',
  814. action='store_true', dest='prefer_ffmpeg',
  815. help='Prefer ffmpeg over avconv for running the postprocessors (default)')
  816. postproc.add_option(
  817. '--ffmpeg-location', '--avconv-location', metavar='PATH',
  818. dest='ffmpeg_location',
  819. help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
  820. postproc.add_option(
  821. '--exec',
  822. metavar='CMD', dest='exec_cmd',
  823. help='Execute a command on the file after downloading and post-processing, similar to find\'s -exec syntax. Example: --exec \'adb push {} /sdcard/Music/ && rm {}\'')
  824. postproc.add_option(
  825. '--convert-subs', '--convert-subtitles',
  826. metavar='FORMAT', dest='convertsubtitles', default=None,
  827. help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
  828. parser.add_option_group(general)
  829. parser.add_option_group(network)
  830. parser.add_option_group(geo)
  831. parser.add_option_group(selection)
  832. parser.add_option_group(downloader)
  833. parser.add_option_group(filesystem)
  834. parser.add_option_group(thumbnail)
  835. parser.add_option_group(verbosity)
  836. parser.add_option_group(workarounds)
  837. parser.add_option_group(video_format)
  838. parser.add_option_group(subtitles)
  839. parser.add_option_group(authentication)
  840. parser.add_option_group(adobe_pass)
  841. parser.add_option_group(postproc)
  842. if overrideArguments is not None:
  843. opts, args = parser.parse_args(overrideArguments)
  844. if opts.verbose:
  845. write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
  846. else:
  847. def compat_conf(conf):
  848. if sys.version_info < (3,):
  849. return [a.decode(preferredencoding(), 'replace') for a in conf]
  850. return conf
  851. command_line_conf = compat_conf(sys.argv[1:])
  852. opts, args = parser.parse_args(command_line_conf)
  853. system_conf = user_conf = custom_conf = []
  854. if '--config-location' in command_line_conf:
  855. location = compat_expanduser(opts.config_location)
  856. if os.path.isdir(location):
  857. location = os.path.join(location, 'youtube-dl.conf')
  858. if not os.path.exists(location):
  859. parser.error('config-location %s does not exist.' % location)
  860. custom_conf = _readOptions(location)
  861. elif '--ignore-config' in command_line_conf:
  862. pass
  863. else:
  864. system_conf = _readOptions('/etc/youtube-dl.conf')
  865. if '--ignore-config' not in system_conf:
  866. user_conf = _readUserConf()
  867. argv = system_conf + user_conf + custom_conf + command_line_conf
  868. opts, args = parser.parse_args(argv)
  869. if opts.verbose:
  870. for conf_label, conf in (
  871. ('System config', system_conf),
  872. ('User config', user_conf),
  873. ('Custom config', custom_conf),
  874. ('Command-line args', command_line_conf)):
  875. write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
  876. return parser, opts, args