You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

828 lines
38 KiB

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