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.

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