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.

571 lines
22 KiB

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