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. ArteTvIE(),
  323. GenericIE()
  324. ]
  325. def _real_main():
  326. parser, opts, args = parseOpts()
  327. # Open appropriate CookieJar
  328. if opts.cookiefile is None:
  329. jar = cookielib.CookieJar()
  330. else:
  331. try:
  332. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  333. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  334. jar.load()
  335. except (IOError, OSError), err:
  336. sys.exit(u'ERROR: unable to open cookie file')
  337. # Set user agent
  338. if opts.user_agent is not None:
  339. std_headers['User-Agent'] = opts.user_agent
  340. # Dump user agent
  341. if opts.dump_user_agent:
  342. print std_headers['User-Agent']
  343. sys.exit(0)
  344. # Batch file verification
  345. batchurls = []
  346. if opts.batchfile is not None:
  347. try:
  348. if opts.batchfile == '-':
  349. batchfd = sys.stdin
  350. else:
  351. batchfd = open(opts.batchfile, 'r')
  352. batchurls = batchfd.readlines()
  353. batchurls = [x.strip() for x in batchurls]
  354. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  355. except IOError:
  356. sys.exit(u'ERROR: batch file could not be read')
  357. all_urls = batchurls + args
  358. all_urls = map(lambda url: url.strip(), all_urls)
  359. # General configuration
  360. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  361. proxy_handler = urllib2.ProxyHandler()
  362. opener = urllib2.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  363. urllib2.install_opener(opener)
  364. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  365. extractors = gen_extractors()
  366. if opts.list_extractors:
  367. for ie in extractors:
  368. print(ie.IE_NAME)
  369. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  370. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  371. for mu in matchedUrls:
  372. print(u' ' + mu)
  373. sys.exit(0)
  374. # Conflicting, missing and erroneous options
  375. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  376. parser.error(u'using .netrc conflicts with giving username/password')
  377. if opts.password is not None and opts.username is None:
  378. parser.error(u'account username missing')
  379. if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
  380. parser.error(u'using output template conflicts with using title, video ID or auto number')
  381. if opts.usetitle and opts.useid:
  382. parser.error(u'using title conflicts with using video ID')
  383. if opts.username is not None and opts.password is None:
  384. opts.password = getpass.getpass(u'Type account password and press return:')
  385. if opts.ratelimit is not None:
  386. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  387. if numeric_limit is None:
  388. parser.error(u'invalid rate limit specified')
  389. opts.ratelimit = numeric_limit
  390. if opts.retries is not None:
  391. try:
  392. opts.retries = long(opts.retries)
  393. except (TypeError, ValueError), err:
  394. parser.error(u'invalid retry count specified')
  395. if opts.buffersize is not None:
  396. numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
  397. if numeric_buffersize is None:
  398. parser.error(u'invalid buffer size specified')
  399. opts.buffersize = numeric_buffersize
  400. try:
  401. opts.playliststart = int(opts.playliststart)
  402. if opts.playliststart <= 0:
  403. raise ValueError(u'Playlist start must be positive')
  404. except (TypeError, ValueError), err:
  405. parser.error(u'invalid playlist start number specified')
  406. try:
  407. opts.playlistend = int(opts.playlistend)
  408. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  409. raise ValueError(u'Playlist end must be greater than playlist start')
  410. except (TypeError, ValueError), err:
  411. parser.error(u'invalid playlist end number specified')
  412. if opts.extractaudio:
  413. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  414. parser.error(u'invalid audio format specified')
  415. if opts.audioquality:
  416. opts.audioquality = opts.audioquality.strip('k').strip('K')
  417. if not opts.audioquality.isdigit():
  418. parser.error(u'invalid audio quality specified')
  419. # File downloader
  420. fd = FileDownloader({
  421. 'usenetrc': opts.usenetrc,
  422. 'username': opts.username,
  423. 'password': opts.password,
  424. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  425. 'forceurl': opts.geturl,
  426. 'forcetitle': opts.gettitle,
  427. 'forcethumbnail': opts.getthumbnail,
  428. 'forcedescription': opts.getdescription,
  429. 'forcefilename': opts.getfilename,
  430. 'forceformat': opts.getformat,
  431. 'simulate': opts.simulate,
  432. '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),
  433. 'format': opts.format,
  434. 'format_limit': opts.format_limit,
  435. 'listformats': opts.listformats,
  436. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  437. or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  438. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  439. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  440. or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
  441. or (opts.useid and u'%(id)s.%(ext)s')
  442. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  443. or u'%(id)s.%(ext)s'),
  444. 'restrictfilenames': opts.restrictfilenames,
  445. 'ignoreerrors': opts.ignoreerrors,
  446. 'ratelimit': opts.ratelimit,
  447. 'nooverwrites': opts.nooverwrites,
  448. 'retries': opts.retries,
  449. 'buffersize': opts.buffersize,
  450. 'noresizebuffer': opts.noresizebuffer,
  451. 'continuedl': opts.continue_dl,
  452. 'noprogress': opts.noprogress,
  453. 'playliststart': opts.playliststart,
  454. 'playlistend': opts.playlistend,
  455. 'logtostderr': opts.outtmpl == '-',
  456. 'consoletitle': opts.consoletitle,
  457. 'nopart': opts.nopart,
  458. 'updatetime': opts.updatetime,
  459. 'writedescription': opts.writedescription,
  460. 'writeinfojson': opts.writeinfojson,
  461. 'writesubtitles': opts.writesubtitles,
  462. 'subtitleslang': opts.subtitleslang,
  463. 'matchtitle': opts.matchtitle,
  464. 'rejecttitle': opts.rejecttitle,
  465. 'max_downloads': opts.max_downloads,
  466. 'prefer_free_formats': opts.prefer_free_formats,
  467. 'verbose': opts.verbose,
  468. })
  469. if opts.verbose:
  470. fd.to_screen(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  471. for extractor in extractors:
  472. fd.add_info_extractor(extractor)
  473. # PostProcessors
  474. if opts.extractaudio:
  475. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  476. # Update version
  477. if opts.update_self:
  478. updateSelf(fd, sys.argv[0])
  479. # Maybe do nothing
  480. if len(all_urls) < 1:
  481. if not opts.update_self:
  482. parser.error(u'you must provide at least one URL')
  483. else:
  484. sys.exit()
  485. try:
  486. retcode = fd.download(all_urls)
  487. except MaxDownloadsReached:
  488. fd.to_screen(u'--max-download limit reached, aborting.')
  489. retcode = 101
  490. # Dump cookie jar if requested
  491. if opts.cookiefile is not None:
  492. try:
  493. jar.save()
  494. except (IOError, OSError), err:
  495. sys.exit(u'ERROR: unable to save cookie jar')
  496. sys.exit(retcode)
  497. def main():
  498. try:
  499. _real_main()
  500. except DownloadError:
  501. sys.exit(1)
  502. except SameFileError:
  503. sys.exit(u'ERROR: fixed output name but more than one file to download')
  504. except KeyboardInterrupt:
  505. sys.exit(u'\nERROR: Interrupted by user')