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.

519 lines
24 KiB

13 years ago
12 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import with_statement
  4. from __future__ import absolute_import
  5. __authors__ = (
  6. 'Ricardo Garcia Gonzalez',
  7. 'Danny Colligan',
  8. 'Benjamin Johnson',
  9. 'Vasyl\' Vavrychuk',
  10. 'Witold Baryluk',
  11. 'Paweł Paprota',
  12. 'Gergely Imreh',
  13. 'Rogério Brito',
  14. 'Philipp Hagemeister',
  15. 'Sören Schulze',
  16. 'Kevin Ngo',
  17. 'Ori Avtalion',
  18. 'shizeeg',
  19. 'Filippo Valsorda',
  20. 'Christian Albrecht',
  21. 'Dave Vasilevsky',
  22. 'Jaime Marquínez Ferrándiz',
  23. 'Jeff Crouse',
  24. 'Osama Khalid',
  25. )
  26. __license__ = 'Public Domain'
  27. import getpass
  28. import optparse
  29. import os
  30. import re
  31. import shlex
  32. import socket
  33. import subprocess
  34. import sys
  35. import warnings
  36. import platform
  37. from .utils import *
  38. from .update import update_self
  39. from .version import __version__
  40. from .FileDownloader import *
  41. from .InfoExtractors import gen_extractors
  42. from .PostProcessor import *
  43. def parseOpts():
  44. def _readOptions(filename_bytes):
  45. try:
  46. optionf = open(filename_bytes)
  47. except IOError:
  48. return [] # silently skip if file is not present
  49. try:
  50. res = []
  51. for l in optionf:
  52. res += shlex.split(l, comments=True)
  53. finally:
  54. optionf.close()
  55. return res
  56. def _format_option_string(option):
  57. ''' ('-o', '--option') -> -o, --format METAVAR'''
  58. opts = []
  59. if option._short_opts:
  60. opts.append(option._short_opts[0])
  61. if option._long_opts:
  62. opts.append(option._long_opts[0])
  63. if len(opts) > 1:
  64. opts.insert(1, ', ')
  65. if option.takes_value(): opts.append(' %s' % option.metavar)
  66. return "".join(opts)
  67. def _find_term_columns():
  68. columns = os.environ.get('COLUMNS', None)
  69. if columns:
  70. return int(columns)
  71. try:
  72. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  73. out,err = sp.communicate()
  74. return int(out.split()[1])
  75. except:
  76. pass
  77. return None
  78. max_width = 80
  79. max_help_position = 80
  80. # No need to wrap help messages if we're on a wide console
  81. columns = _find_term_columns()
  82. if columns: max_width = columns
  83. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  84. fmt.format_option_strings = _format_option_string
  85. kw = {
  86. 'version' : __version__,
  87. 'formatter' : fmt,
  88. 'usage' : '%prog [options] url [url...]',
  89. 'conflict_handler' : 'resolve',
  90. }
  91. parser = optparse.OptionParser(**kw)
  92. # option groups
  93. general = optparse.OptionGroup(parser, 'General Options')
  94. selection = optparse.OptionGroup(parser, 'Video Selection')
  95. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  96. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  97. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  98. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  99. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  100. general.add_option('-h', '--help',
  101. action='help', help='print this help text and exit')
  102. general.add_option('-v', '--version',
  103. action='version', help='print program version and exit')
  104. general.add_option('-U', '--update',
  105. action='store_true', dest='update_self', help='update this program to latest version')
  106. general.add_option('-i', '--ignore-errors',
  107. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  108. general.add_option('-r', '--rate-limit',
  109. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  110. general.add_option('-R', '--retries',
  111. dest='retries', metavar='RETRIES', help='number of retries (default is %default)', default=10)
  112. general.add_option('--buffer-size',
  113. dest='buffersize', metavar='SIZE', help='size of download buffer (e.g. 1024 or 16k) (default is %default)', default="1024")
  114. general.add_option('--no-resize-buffer',
  115. action='store_true', dest='noresizebuffer',
  116. help='do not automatically adjust the buffer size. By default, the buffer size is automatically resized from an initial value of SIZE.', default=False)
  117. general.add_option('--dump-user-agent',
  118. action='store_true', dest='dump_user_agent',
  119. help='display the current browser identification', default=False)
  120. general.add_option('--user-agent',
  121. dest='user_agent', help='specify a custom user agent', metavar='UA')
  122. general.add_option('--list-extractors',
  123. action='store_true', dest='list_extractors',
  124. help='List all supported extractors and the URLs they would handle', default=False)
  125. general.add_option('--test', action='store_true', dest='test', default=False, help=optparse.SUPPRESS_HELP)
  126. selection.add_option('--playlist-start',
  127. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is %default)', default=1)
  128. selection.add_option('--playlist-end',
  129. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  130. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  131. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  132. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  133. selection.add_option('--min-filesize', metavar='SIZE', dest='min_filesize', help="Do not download any videos smaller than SIZE (e.g. 50k or 44.6m)", default=None)
  134. selection.add_option('--max-filesize', metavar='SIZE', dest='max_filesize', help="Do not download any videos larger than SIZE (e.g. 50k or 44.6m)", default=None)
  135. authentication.add_option('-u', '--username',
  136. dest='username', metavar='USERNAME', help='account username')
  137. authentication.add_option('-p', '--password',
  138. dest='password', metavar='PASSWORD', help='account password')
  139. authentication.add_option('-n', '--netrc',
  140. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  141. video_format.add_option('-f', '--format',
  142. action='store', dest='format', metavar='FORMAT', help='video format code')
  143. video_format.add_option('--all-formats',
  144. action='store_const', dest='format', help='download all available video formats', const='all')
  145. video_format.add_option('--prefer-free-formats',
  146. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  147. video_format.add_option('--max-quality',
  148. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  149. video_format.add_option('-F', '--list-formats',
  150. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  151. video_format.add_option('--write-srt',
  152. action='store_true', dest='writesubtitles',
  153. help='write video closed captions to a .srt file (currently youtube only)', default=False)
  154. video_format.add_option('--srt-lang',
  155. action='store', dest='subtitleslang', metavar='LANG',
  156. help='language of the closed captions to download (optional) use IETF language tags like \'en\'')
  157. verbosity.add_option('-q', '--quiet',
  158. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  159. verbosity.add_option('-s', '--simulate',
  160. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  161. verbosity.add_option('--skip-download',
  162. action='store_true', dest='skip_download', help='do not download the video', default=False)
  163. verbosity.add_option('-g', '--get-url',
  164. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  165. verbosity.add_option('-e', '--get-title',
  166. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  167. verbosity.add_option('--get-thumbnail',
  168. action='store_true', dest='getthumbnail',
  169. help='simulate, quiet but print thumbnail URL', default=False)
  170. verbosity.add_option('--get-description',
  171. action='store_true', dest='getdescription',
  172. help='simulate, quiet but print video description', default=False)
  173. verbosity.add_option('--get-filename',
  174. action='store_true', dest='getfilename',
  175. help='simulate, quiet but print output filename', default=False)
  176. verbosity.add_option('--get-format',
  177. action='store_true', dest='getformat',
  178. help='simulate, quiet but print output format', default=False)
  179. verbosity.add_option('--no-progress',
  180. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  181. verbosity.add_option('--console-title',
  182. action='store_true', dest='consoletitle',
  183. help='display progress in console titlebar', default=False)
  184. verbosity.add_option('-v', '--verbose',
  185. action='store_true', dest='verbose', help='print various debugging information', default=False)
  186. filesystem.add_option('-t', '--title',
  187. action='store_true', dest='usetitle', help='use title in file name', default=False)
  188. filesystem.add_option('--id',
  189. action='store_true', dest='useid', help='use video ID in file name', default=False)
  190. filesystem.add_option('-l', '--literal',
  191. action='store_true', dest='usetitle', help='[deprecated] alias of --title', default=False)
  192. filesystem.add_option('-A', '--auto-number',
  193. action='store_true', dest='autonumber',
  194. help='number downloaded files starting from 00000', default=False)
  195. filesystem.add_option('-o', '--output',
  196. dest='outtmpl', metavar='TEMPLATE', help='output filename template. Use %(title)s to get the title, %(uploader)s for the uploader name, %(uploader_id)s for the uploader nickname if different, %(autonumber)s to get an automatically incremented number, %(ext)s for the filename extension, %(upload_date)s for the upload date (YYYYMMDD), %(extractor)s for the provider (youtube, metacafe, etc), %(id)s for the video id and %% for a literal percent. Use - to output to stdout. Can also be used to download to a different directory, for example with -o \'/my/downloads/%(uploader)s/%(title)s-%(id)s.%(ext)s\' .')
  197. filesystem.add_option('--restrict-filenames',
  198. action='store_true', dest='restrictfilenames',
  199. help='Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames', default=False)
  200. filesystem.add_option('-a', '--batch-file',
  201. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  202. filesystem.add_option('-w', '--no-overwrites',
  203. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  204. filesystem.add_option('-c', '--continue',
  205. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  206. filesystem.add_option('--no-continue',
  207. action='store_false', dest='continue_dl',
  208. help='do not resume partially downloaded files (restart from beginning)')
  209. filesystem.add_option('--cookies',
  210. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  211. filesystem.add_option('--no-part',
  212. action='store_true', dest='nopart', help='do not use .part files', default=False)
  213. filesystem.add_option('--no-mtime',
  214. action='store_false', dest='updatetime',
  215. help='do not use the Last-modified header to set the file modification time', default=True)
  216. filesystem.add_option('--write-description',
  217. action='store_true', dest='writedescription',
  218. help='write video description to a .description file', default=False)
  219. filesystem.add_option('--write-info-json',
  220. action='store_true', dest='writeinfojson',
  221. help='write video metadata to a .info.json file', default=False)
  222. postproc.add_option('-x', '--extract-audio', action='store_true', dest='extractaudio', default=False,
  223. help='convert video files to audio-only files (requires ffmpeg or avconv and ffprobe or avprobe)')
  224. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  225. help='"best", "aac", "vorbis", "mp3", "m4a", "opus", or "wav"; best by default')
  226. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='5',
  227. help='ffmpeg/avconv audio quality specification, insert a value between 0 (better) and 9 (worse) for VBR or a specific bitrate like 128K (default 5)')
  228. postproc.add_option('--recode-video', metavar='FORMAT', dest='recodevideo', default=None,
  229. help='Encode the video to another format if necessary (currently supported: mp4|flv|ogg|webm)')
  230. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  231. help='keeps the video file on disk after the post-processing; the video is erased by default')
  232. postproc.add_option('--no-post-overwrites', action='store_true', dest='nopostoverwrites', default=False,
  233. help='do not overwrite post-processed files; the post-processed files are overwritten by default')
  234. parser.add_option_group(general)
  235. parser.add_option_group(selection)
  236. parser.add_option_group(filesystem)
  237. parser.add_option_group(verbosity)
  238. parser.add_option_group(video_format)
  239. parser.add_option_group(authentication)
  240. parser.add_option_group(postproc)
  241. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  242. if xdg_config_home:
  243. userConf = os.path.join(xdg_config_home, 'youtube-dl.conf')
  244. else:
  245. userConf = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  246. argv = _readOptions('/etc/youtube-dl.conf') + _readOptions(userConf) + sys.argv[1:]
  247. opts, args = parser.parse_args(argv)
  248. return parser, opts, args
  249. def _real_main():
  250. parser, opts, args = parseOpts()
  251. # Open appropriate CookieJar
  252. if opts.cookiefile is None:
  253. jar = compat_cookiejar.CookieJar()
  254. else:
  255. try:
  256. jar = compat_cookiejar.MozillaCookieJar(opts.cookiefile)
  257. if os.access(opts.cookiefile, os.R_OK):
  258. jar.load()
  259. except (IOError, OSError) as err:
  260. if opts.verbose:
  261. traceback.print_exc()
  262. sys.stderr.write(u'ERROR: unable to open cookie file\n')
  263. sys.exit(101)
  264. # Set user agent
  265. if opts.user_agent is not None:
  266. std_headers['User-Agent'] = opts.user_agent
  267. # Dump user agent
  268. if opts.dump_user_agent:
  269. print(std_headers['User-Agent'])
  270. sys.exit(0)
  271. # Batch file verification
  272. batchurls = []
  273. if opts.batchfile is not None:
  274. try:
  275. if opts.batchfile == '-':
  276. batchfd = sys.stdin
  277. else:
  278. batchfd = open(opts.batchfile, 'r')
  279. batchurls = batchfd.readlines()
  280. batchurls = [x.strip() for x in batchurls]
  281. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  282. except IOError:
  283. sys.exit(u'ERROR: batch file could not be read')
  284. all_urls = batchurls + args
  285. all_urls = [url.strip() for url in all_urls]
  286. # General configuration
  287. cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
  288. proxy_handler = compat_urllib_request.ProxyHandler()
  289. opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  290. compat_urllib_request.install_opener(opener)
  291. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  292. extractors = gen_extractors()
  293. if opts.list_extractors:
  294. for ie in extractors:
  295. print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
  296. matchedUrls = [url for url in all_urls if ie.suitable(url)]
  297. all_urls = [url for url in all_urls if url not in matchedUrls]
  298. for mu in matchedUrls:
  299. print(u' ' + mu)
  300. sys.exit(0)
  301. # Conflicting, missing and erroneous options
  302. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  303. parser.error(u'using .netrc conflicts with giving username/password')
  304. if opts.password is not None and opts.username is None:
  305. parser.error(u'account username missing')
  306. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  307. parser.error(u'using output template conflicts with using title, video ID or auto number')
  308. if opts.usetitle and opts.useid:
  309. parser.error(u'using title conflicts with using video ID')
  310. if opts.username is not None and opts.password is None:
  311. opts.password = getpass.getpass(u'Type account password and press return:')
  312. if opts.ratelimit is not None:
  313. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  314. if numeric_limit is None:
  315. parser.error(u'invalid rate limit specified')
  316. opts.ratelimit = numeric_limit
  317. if opts.min_filesize is not None:
  318. numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
  319. if numeric_limit is None:
  320. parser.error(u'invalid min_filesize specified')
  321. opts.min_filesize = numeric_limit
  322. if opts.max_filesize is not None:
  323. numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
  324. if numeric_limit is None:
  325. parser.error(u'invalid max_filesize specified')
  326. opts.max_filesize = numeric_limit
  327. if opts.retries is not None:
  328. try:
  329. opts.retries = int(opts.retries)
  330. except (TypeError, ValueError) as err:
  331. parser.error(u'invalid retry count specified')
  332. if opts.buffersize is not None:
  333. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  334. if numeric_buffersize is None:
  335. parser.error(u'invalid buffer size specified')
  336. opts.buffersize = numeric_buffersize
  337. try:
  338. opts.playliststart = int(opts.playliststart)
  339. if opts.playliststart <= 0:
  340. raise ValueError(u'Playlist start must be positive')
  341. except (TypeError, ValueError) as err:
  342. parser.error(u'invalid playlist start number specified')
  343. try:
  344. opts.playlistend = int(opts.playlistend)
  345. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  346. raise ValueError(u'Playlist end must be greater than playlist start')
  347. except (TypeError, ValueError) as err:
  348. parser.error(u'invalid playlist end number specified')
  349. if opts.extractaudio:
  350. if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
  351. parser.error(u'invalid audio format specified')
  352. if opts.audioquality:
  353. opts.audioquality = opts.audioquality.strip('k').strip('K')
  354. if not opts.audioquality.isdigit():
  355. parser.error(u'invalid audio quality specified')
  356. if opts.recodevideo is not None:
  357. if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg']:
  358. parser.error(u'invalid video recode format specified')
  359. if sys.version_info < (3,):
  360. # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
  361. if opts.outtmpl is not None:
  362. opts.outtmpl = opts.outtmpl.decode(preferredencoding())
  363. outtmpl =((opts.outtmpl is not None and opts.outtmpl)
  364. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  365. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  366. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  367. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  368. or (opts.useid and u'%(id)s.%(ext)s')
  369. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  370. or u'%(id)s.%(ext)s')
  371. # File downloader
  372. fd = FileDownloader({
  373. 'usenetrc': opts.usenetrc,
  374. 'username': opts.username,
  375. 'password': opts.password,
  376. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  377. 'forceurl': opts.geturl,
  378. 'forcetitle': opts.gettitle,
  379. 'forcethumbnail': opts.getthumbnail,
  380. 'forcedescription': opts.getdescription,
  381. 'forcefilename': opts.getfilename,
  382. 'forceformat': opts.getformat,
  383. 'simulate': opts.simulate,
  384. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  385. 'format': opts.format,
  386. 'format_limit': opts.format_limit,
  387. 'listformats': opts.listformats,
  388. 'outtmpl': outtmpl,
  389. 'restrictfilenames': opts.restrictfilenames,
  390. 'ignoreerrors': opts.ignoreerrors,
  391. 'ratelimit': opts.ratelimit,
  392. 'nooverwrites': opts.nooverwrites,
  393. 'retries': opts.retries,
  394. 'buffersize': opts.buffersize,
  395. 'noresizebuffer': opts.noresizebuffer,
  396. 'continuedl': opts.continue_dl,
  397. 'noprogress': opts.noprogress,
  398. 'playliststart': opts.playliststart,
  399. 'playlistend': opts.playlistend,
  400. 'logtostderr': opts.outtmpl == '-',
  401. 'consoletitle': opts.consoletitle,
  402. 'nopart': opts.nopart,
  403. 'updatetime': opts.updatetime,
  404. 'writedescription': opts.writedescription,
  405. 'writeinfojson': opts.writeinfojson,
  406. 'writesubtitles': opts.writesubtitles,
  407. 'subtitleslang': opts.subtitleslang,
  408. 'matchtitle': opts.matchtitle,
  409. 'rejecttitle': opts.rejecttitle,
  410. 'max_downloads': opts.max_downloads,
  411. 'prefer_free_formats': opts.prefer_free_formats,
  412. 'verbose': opts.verbose,
  413. 'test': opts.test,
  414. 'keepvideo': opts.keepvideo,
  415. 'min_filesize': opts.min_filesize,
  416. 'max_filesize': opts.max_filesize
  417. })
  418. if opts.verbose:
  419. fd.to_screen(u'[debug] youtube-dl version ' + __version__)
  420. try:
  421. sp = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  422. cwd=os.path.dirname(os.path.abspath(__file__)))
  423. out, err = sp.communicate()
  424. out = out.decode().strip()
  425. if re.match('[0-9a-f]+', out):
  426. fd.to_screen(u'[debug] Git HEAD: ' + out)
  427. except:
  428. pass
  429. fd.to_screen(u'[debug] Python version %s - %s' %(platform.python_version(), platform.platform()))
  430. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  431. for extractor in extractors:
  432. fd.add_info_extractor(extractor)
  433. # PostProcessors
  434. if opts.extractaudio:
  435. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
  436. if opts.recodevideo:
  437. fd.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
  438. # Update version
  439. if opts.update_self:
  440. update_self(fd.to_screen, opts.verbose, sys.argv[0])
  441. # Maybe do nothing
  442. if len(all_urls) < 1:
  443. if not opts.update_self:
  444. parser.error(u'you must provide at least one URL')
  445. else:
  446. sys.exit()
  447. try:
  448. retcode = fd.download(all_urls)
  449. except MaxDownloadsReached:
  450. fd.to_screen(u'--max-download limit reached, aborting.')
  451. retcode = 101
  452. # Dump cookie jar if requested
  453. if opts.cookiefile is not None:
  454. try:
  455. jar.save()
  456. except (IOError, OSError) as err:
  457. sys.exit(u'ERROR: unable to save cookie jar')
  458. sys.exit(retcode)
  459. def main():
  460. try:
  461. _real_main()
  462. except DownloadError:
  463. sys.exit(1)
  464. except SameFileError:
  465. sys.exit(u'ERROR: fixed output name but more than one file to download')
  466. except KeyboardInterrupt:
  467. sys.exit(u'\nERROR: Interrupted by user')