options.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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 (regex or caseless sub-string)')
  247. selection.add_option(
  248. '--reject-title',
  249. dest='rejecttitle', metavar='REGEX',
  250. help='Skip download for matching titles (regex or caseless 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, smotri, 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. '--autonumber-size',
  659. dest='autonumber_size', metavar='NUMBER', type=int,
  660. help=optparse.SUPPRESS_HELP)
  661. filesystem.add_option(
  662. '--autonumber-start',
  663. dest='autonumber_start', metavar='NUMBER', default=1, type=int,
  664. help='Specify the start value for %(autonumber)s (default is %default)')
  665. filesystem.add_option(
  666. '--restrict-filenames',
  667. action='store_true', dest='restrictfilenames', default=False,
  668. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames')
  669. filesystem.add_option(
  670. '-A', '--auto-number',
  671. action='store_true', dest='autonumber', default=False,
  672. help=optparse.SUPPRESS_HELP)
  673. filesystem.add_option(
  674. '-t', '--title',
  675. action='store_true', dest='usetitle', default=False,
  676. help=optparse.SUPPRESS_HELP)
  677. filesystem.add_option(
  678. '-l', '--literal', default=False,
  679. action='store_true', dest='usetitle',
  680. help=optparse.SUPPRESS_HELP)
  681. filesystem.add_option(
  682. '-w', '--no-overwrites',
  683. action='store_true', dest='nooverwrites', default=False,
  684. help='Do not overwrite files')
  685. filesystem.add_option(
  686. '-c', '--continue',
  687. action='store_true', dest='continue_dl', default=True,
  688. help='Force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.')
  689. filesystem.add_option(
  690. '--no-continue',
  691. action='store_false', dest='continue_dl',
  692. help='Do not resume partially downloaded files (restart from beginning)')
  693. filesystem.add_option(
  694. '--no-part',
  695. action='store_true', dest='nopart', default=False,
  696. help='Do not use .part files - write directly into output file')
  697. filesystem.add_option(
  698. '--no-mtime',
  699. action='store_false', dest='updatetime', default=True,
  700. help='Do not use the Last-modified header to set the file modification time')
  701. filesystem.add_option(
  702. '--write-description',
  703. action='store_true', dest='writedescription', default=False,
  704. help='Write video description to a .description file')
  705. filesystem.add_option(
  706. '--write-info-json',
  707. action='store_true', dest='writeinfojson', default=False,
  708. help='Write video metadata to a .info.json file')
  709. filesystem.add_option(
  710. '--write-annotations',
  711. action='store_true', dest='writeannotations', default=False,
  712. help='Write video annotations to a .annotations.xml file')
  713. filesystem.add_option(
  714. '--load-info-json', '--load-info',
  715. dest='load_info_filename', metavar='FILE',
  716. help='JSON file containing the video information (created with the "--write-info-json" option)')
  717. filesystem.add_option(
  718. '--cookies',
  719. dest='cookiefile', metavar='FILE',
  720. help='File to read cookies from and dump cookie jar in')
  721. filesystem.add_option(
  722. '--cache-dir', dest='cachedir', default=None, metavar='DIR',
  723. 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.')
  724. filesystem.add_option(
  725. '--no-cache-dir', action='store_const', const=False, dest='cachedir',
  726. help='Disable filesystem caching')
  727. filesystem.add_option(
  728. '--rm-cache-dir',
  729. action='store_true', dest='rm_cachedir',
  730. help='Delete all filesystem cache files')
  731. thumbnail = optparse.OptionGroup(parser, 'Thumbnail images')
  732. thumbnail.add_option(
  733. '--write-thumbnail',
  734. action='store_true', dest='writethumbnail', default=False,
  735. help='Write thumbnail image to disk')
  736. thumbnail.add_option(
  737. '--write-all-thumbnails',
  738. action='store_true', dest='write_all_thumbnails', default=False,
  739. help='Write all thumbnail image formats to disk')
  740. thumbnail.add_option(
  741. '--list-thumbnails',
  742. action='store_true', dest='list_thumbnails', default=False,
  743. help='Simulate and list all available thumbnail formats')
  744. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  745. postproc.add_option(
  746. '-x', '--extract-audio',
  747. action='store_true', dest='extractaudio', default=False,
  748. help='Convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  749. postproc.add_option(
  750. '--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  751. help='Specify audio format: "best", "aac", "flac", "mp3", "m4a", "opus", "vorbis", or "wav"; "%default" by default; No effect without -x')
  752. postproc.add_option(
  753. '--audio-quality', metavar='QUALITY',
  754. dest='audioquality', default='5',
  755. 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)')
  756. postproc.add_option(
  757. '--recode-video',
  758. metavar='FORMAT', dest='recodevideo', default=None,
  759. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm|mkv|avi)')
  760. postproc.add_option(
  761. '--postprocessor-args',
  762. dest='postprocessor_args', metavar='ARGS',
  763. help='Give these arguments to the postprocessor')
  764. postproc.add_option(
  765. '-k', '--keep-video',
  766. action='store_true', dest='keepvideo', default=False,
  767. help='Keep the video file on disk after the post-processing; the video is erased by default')
  768. postproc.add_option(
  769. '--no-post-overwrites',
  770. action='store_true', dest='nopostoverwrites', default=False,
  771. help='Do not overwrite post-processed files; the post-processed files are overwritten by default')
  772. postproc.add_option(
  773. '--embed-subs',
  774. action='store_true', dest='embedsubtitles', default=False,
  775. help='Embed subtitles in the video (only for mp4, webm and mkv videos)')
  776. postproc.add_option(
  777. '--embed-thumbnail',
  778. action='store_true', dest='embedthumbnail', default=False,
  779. help='Embed thumbnail in the audio as cover art')
  780. postproc.add_option(
  781. '--add-metadata',
  782. action='store_true', dest='addmetadata', default=False,
  783. help='Write metadata to the video file')
  784. postproc.add_option(
  785. '--metadata-from-title',
  786. metavar='FORMAT', dest='metafromtitle',
  787. help='Parse additional metadata like song title / artist from the video title. '
  788. 'The format syntax is the same as --output. Regular expression with '
  789. 'named capture groups may also be used. '
  790. 'The parsed parameters replace existing values. '
  791. 'Example: --metadata-from-title "%(artist)s - %(title)s" matches a title like '
  792. '"Coldplay - Paradise". '
  793. 'Example (regex): --metadata-from-title "(?P<artist>.+?) - (?P<title>.+)"')
  794. postproc.add_option(
  795. '--xattrs',
  796. action='store_true', dest='xattrs', default=False,
  797. help='Write metadata to the video file\'s xattrs (using dublin core and xdg standards)')
  798. postproc.add_option(
  799. '--fixup',
  800. metavar='POLICY', dest='fixup', default='detect_or_warn',
  801. help='Automatically correct known faults of the file. '
  802. 'One of never (do nothing), warn (only emit a warning), '
  803. 'detect_or_warn (the default; fix file if we can, warn otherwise)')
  804. postproc.add_option(
  805. '--prefer-avconv',
  806. action='store_false', dest='prefer_ffmpeg',
  807. help='Prefer avconv over ffmpeg for running the postprocessors')
  808. postproc.add_option(
  809. '--prefer-ffmpeg',
  810. action='store_true', dest='prefer_ffmpeg',
  811. help='Prefer ffmpeg over avconv for running the postprocessors (default)')
  812. postproc.add_option(
  813. '--ffmpeg-location', '--avconv-location', metavar='PATH',
  814. dest='ffmpeg_location',
  815. help='Location of the ffmpeg/avconv binary; either the path to the binary or its containing directory.')
  816. postproc.add_option(
  817. '--exec',
  818. metavar='CMD', dest='exec_cmd',
  819. 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 {}\'')
  820. postproc.add_option(
  821. '--convert-subs', '--convert-subtitles',
  822. metavar='FORMAT', dest='convertsubtitles', default=None,
  823. help='Convert the subtitles to other format (currently supported: srt|ass|vtt|lrc)')
  824. parser.add_option_group(general)
  825. parser.add_option_group(network)
  826. parser.add_option_group(geo)
  827. parser.add_option_group(selection)
  828. parser.add_option_group(downloader)
  829. parser.add_option_group(filesystem)
  830. parser.add_option_group(thumbnail)
  831. parser.add_option_group(verbosity)
  832. parser.add_option_group(workarounds)
  833. parser.add_option_group(video_format)
  834. parser.add_option_group(subtitles)
  835. parser.add_option_group(authentication)
  836. parser.add_option_group(adobe_pass)
  837. parser.add_option_group(postproc)
  838. if overrideArguments is not None:
  839. opts, args = parser.parse_args(overrideArguments)
  840. if opts.verbose:
  841. write_string('[debug] Override config: ' + repr(overrideArguments) + '\n')
  842. else:
  843. def compat_conf(conf):
  844. if sys.version_info < (3,):
  845. return [a.decode(preferredencoding(), 'replace') for a in conf]
  846. return conf
  847. command_line_conf = compat_conf(sys.argv[1:])
  848. opts, args = parser.parse_args(command_line_conf)
  849. system_conf = user_conf = custom_conf = []
  850. if '--config-location' in command_line_conf:
  851. location = compat_expanduser(opts.config_location)
  852. if os.path.isdir(location):
  853. location = os.path.join(location, 'youtube-dl.conf')
  854. if not os.path.exists(location):
  855. parser.error('config-location %s does not exist.' % location)
  856. custom_conf = _readOptions(location)
  857. elif '--ignore-config' in command_line_conf:
  858. pass
  859. else:
  860. system_conf = _readOptions('/etc/youtube-dl.conf')
  861. if '--ignore-config' not in system_conf:
  862. user_conf = _readUserConf()
  863. argv = system_conf + user_conf + custom_conf + command_line_conf
  864. opts, args = parser.parse_args(argv)
  865. if opts.verbose:
  866. for conf_label, conf in (
  867. ('System config', system_conf),
  868. ('User config', user_conf),
  869. ('Custom config', custom_conf),
  870. ('Command-line args', command_line_conf)):
  871. write_string('[debug] %s: %s\n' % (conf_label, repr(_hide_login_info(conf))))
  872. return parser, opts, args