YoutubeDL.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import io
  5. import os
  6. import re
  7. import shutil
  8. import socket
  9. import sys
  10. import time
  11. import traceback
  12. from .utils import *
  13. from .extractor import get_info_extractor
  14. from .FileDownloader import FileDownloader
  15. class YoutubeDL(object):
  16. """YoutubeDL class.
  17. YoutubeDL objects are the ones responsible of downloading the
  18. actual video file and writing it to disk if the user has requested
  19. it, among some other tasks. In most cases there should be one per
  20. program. As, given a video URL, the downloader doesn't know how to
  21. extract all the needed information, task that InfoExtractors do, it
  22. has to pass the URL to one of them.
  23. For this, YoutubeDL objects have a method that allows
  24. InfoExtractors to be registered in a given order. When it is passed
  25. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  26. finds that reports being able to handle it. The InfoExtractor extracts
  27. all the information about the video or videos the URL refers to, and
  28. YoutubeDL process the extracted information, possibly using a File
  29. Downloader to download the video.
  30. YoutubeDL objects accept a lot of parameters. In order not to saturate
  31. the object constructor with arguments, it receives a dictionary of
  32. options instead. These options are available through the params
  33. attribute for the InfoExtractors to use. The YoutubeDL also
  34. registers itself as the downloader in charge for the InfoExtractors
  35. that are added to it, so this is a "mutual registration".
  36. Available options:
  37. username: Username for authentication purposes.
  38. password: Password for authentication purposes.
  39. usenetrc: Use netrc for authentication instead.
  40. verbose: Print additional info to stdout.
  41. quiet: Do not print messages to stdout.
  42. forceurl: Force printing final URL.
  43. forcetitle: Force printing title.
  44. forceid: Force printing ID.
  45. forcethumbnail: Force printing thumbnail URL.
  46. forcedescription: Force printing description.
  47. forcefilename: Force printing final filename.
  48. simulate: Do not download the video files.
  49. format: Video format code.
  50. format_limit: Highest quality format to try.
  51. outtmpl: Template for output names.
  52. restrictfilenames: Do not allow "&" and spaces in file names
  53. ignoreerrors: Do not stop on download errors.
  54. nooverwrites: Prevent overwriting files.
  55. playliststart: Playlist item to start at.
  56. playlistend: Playlist item to end at.
  57. matchtitle: Download only matching titles.
  58. rejecttitle: Reject downloads for matching titles.
  59. logtostderr: Log messages to stderr instead of stdout.
  60. writedescription: Write the video description to a .description file
  61. writeinfojson: Write the video description to a .info.json file
  62. writethumbnail: Write the thumbnail image to a file
  63. writesubtitles: Write the video subtitles to a file
  64. allsubtitles: Downloads all the subtitles of the video
  65. listsubtitles: Lists all available subtitles for the video
  66. subtitlesformat: Subtitle format [sbv/srt] (default=srt)
  67. subtitleslang: Language of the subtitles to download
  68. keepvideo: Keep the video file after post-processing
  69. daterange: A DateRange object, download only if the upload_date is in the range.
  70. skip_download: Skip the actual download of the video file
  71. The following parameters are not used by YoutubeDL itself, they are used by
  72. the FileDownloader:
  73. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  74. noresizebuffer, retries, continuedl, noprogress, consoletitle
  75. """
  76. params = None
  77. _ies = []
  78. _pps = []
  79. _download_retcode = None
  80. _num_downloads = None
  81. _screen_file = None
  82. def __init__(self, params):
  83. """Create a FileDownloader object with the given options."""
  84. self._ies = []
  85. self._pps = []
  86. self._progress_hooks = []
  87. self._download_retcode = 0
  88. self._num_downloads = 0
  89. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  90. self.params = params
  91. self.fd = FileDownloader(self, self.params)
  92. if '%(stitle)s' in self.params['outtmpl']:
  93. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  94. def add_info_extractor(self, ie):
  95. """Add an InfoExtractor object to the end of the list."""
  96. self._ies.append(ie)
  97. ie.set_downloader(self)
  98. def add_post_processor(self, pp):
  99. """Add a PostProcessor object to the end of the chain."""
  100. self._pps.append(pp)
  101. pp.set_downloader(self)
  102. def to_screen(self, message, skip_eol=False):
  103. """Print message to stdout if not in quiet mode."""
  104. assert type(message) == type(u'')
  105. if not self.params.get('quiet', False):
  106. terminator = [u'\n', u''][skip_eol]
  107. output = message + terminator
  108. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  109. output = output.encode(preferredencoding(), 'ignore')
  110. self._screen_file.write(output)
  111. self._screen_file.flush()
  112. def to_stderr(self, message):
  113. """Print message to stderr."""
  114. assert type(message) == type(u'')
  115. output = message + u'\n'
  116. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  117. output = output.encode(preferredencoding())
  118. sys.stderr.write(output)
  119. def fixed_template(self):
  120. """Checks if the output template is fixed."""
  121. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  122. def trouble(self, message=None, tb=None):
  123. """Determine action to take when a download problem appears.
  124. Depending on if the downloader has been configured to ignore
  125. download errors or not, this method may throw an exception or
  126. not when errors are found, after printing the message.
  127. tb, if given, is additional traceback information.
  128. """
  129. if message is not None:
  130. self.to_stderr(message)
  131. if self.params.get('verbose'):
  132. if tb is None:
  133. if sys.exc_info()[0]: # if .trouble has been called from an except block
  134. tb = u''
  135. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  136. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  137. tb += compat_str(traceback.format_exc())
  138. else:
  139. tb_data = traceback.format_list(traceback.extract_stack())
  140. tb = u''.join(tb_data)
  141. self.to_stderr(tb)
  142. if not self.params.get('ignoreerrors', False):
  143. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  144. exc_info = sys.exc_info()[1].exc_info
  145. else:
  146. exc_info = sys.exc_info()
  147. raise DownloadError(message, exc_info)
  148. self._download_retcode = 1
  149. def report_warning(self, message):
  150. '''
  151. Print the message to stderr, it will be prefixed with 'WARNING:'
  152. If stderr is a tty file the 'WARNING:' will be colored
  153. '''
  154. if sys.stderr.isatty() and os.name != 'nt':
  155. _msg_header=u'\033[0;33mWARNING:\033[0m'
  156. else:
  157. _msg_header=u'WARNING:'
  158. warning_message=u'%s %s' % (_msg_header,message)
  159. self.to_stderr(warning_message)
  160. def report_error(self, message, tb=None):
  161. '''
  162. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  163. in red if stderr is a tty file.
  164. '''
  165. if sys.stderr.isatty() and os.name != 'nt':
  166. _msg_header = u'\033[0;31mERROR:\033[0m'
  167. else:
  168. _msg_header = u'ERROR:'
  169. error_message = u'%s %s' % (_msg_header, message)
  170. self.trouble(error_message, tb)
  171. def slow_down(self, start_time, byte_counter):
  172. """Sleep if the download speed is over the rate limit."""
  173. rate_limit = self.params.get('ratelimit', None)
  174. if rate_limit is None or byte_counter == 0:
  175. return
  176. now = time.time()
  177. elapsed = now - start_time
  178. if elapsed <= 0.0:
  179. return
  180. speed = float(byte_counter) / elapsed
  181. if speed > rate_limit:
  182. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  183. def report_writedescription(self, descfn):
  184. """ Report that the description file is being written """
  185. self.to_screen(u'[info] Writing video description to: ' + descfn)
  186. def report_writesubtitles(self, sub_filename):
  187. """ Report that the subtitles file is being written """
  188. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  189. def report_writeinfojson(self, infofn):
  190. """ Report that the metadata file has been written """
  191. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  192. def report_file_already_downloaded(self, file_name):
  193. """Report file has already been fully downloaded."""
  194. try:
  195. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  196. except (UnicodeEncodeError) as err:
  197. self.to_screen(u'[download] The file has already been downloaded')
  198. def increment_downloads(self):
  199. """Increment the ordinal that assigns a number to each file."""
  200. self._num_downloads += 1
  201. def prepare_filename(self, info_dict):
  202. """Generate the output filename."""
  203. try:
  204. template_dict = dict(info_dict)
  205. template_dict['epoch'] = int(time.time())
  206. autonumber_size = self.params.get('autonumber_size')
  207. if autonumber_size is None:
  208. autonumber_size = 5
  209. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  210. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  211. if template_dict['playlist_index'] is not None:
  212. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  213. sanitize = lambda k,v: sanitize_filename(
  214. u'NA' if v is None else compat_str(v),
  215. restricted=self.params.get('restrictfilenames'),
  216. is_id=(k==u'id'))
  217. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  218. filename = self.params['outtmpl'] % template_dict
  219. return filename
  220. except KeyError as err:
  221. self.report_error(u'Erroneous output template')
  222. return None
  223. except ValueError as err:
  224. self.report_error(u'Insufficient system charset ' + repr(preferredencoding()))
  225. return None
  226. def _match_entry(self, info_dict):
  227. """ Returns None iff the file should be downloaded """
  228. title = info_dict['title']
  229. matchtitle = self.params.get('matchtitle', False)
  230. if matchtitle:
  231. if not re.search(matchtitle, title, re.IGNORECASE):
  232. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  233. rejecttitle = self.params.get('rejecttitle', False)
  234. if rejecttitle:
  235. if re.search(rejecttitle, title, re.IGNORECASE):
  236. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  237. date = info_dict.get('upload_date', None)
  238. if date is not None:
  239. dateRange = self.params.get('daterange', DateRange())
  240. if date not in dateRange:
  241. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  242. return None
  243. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  244. '''
  245. Returns a list with a dictionary for each video we find.
  246. If 'download', also downloads the videos.
  247. extra_info is a dict containing the extra values to add to each result
  248. '''
  249. if ie_key:
  250. ie = get_info_extractor(ie_key)()
  251. ie.set_downloader(self)
  252. ies = [ie]
  253. else:
  254. ies = self._ies
  255. for ie in ies:
  256. if not ie.suitable(url):
  257. continue
  258. if not ie.working():
  259. self.report_warning(u'The program functionality for this site has been marked as broken, '
  260. u'and will probably not work.')
  261. try:
  262. ie_result = ie.extract(url)
  263. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  264. break
  265. if isinstance(ie_result, list):
  266. # Backwards compatibility: old IE result format
  267. for result in ie_result:
  268. result.update(extra_info)
  269. ie_result = {
  270. '_type': 'compat_list',
  271. 'entries': ie_result,
  272. }
  273. else:
  274. ie_result.update(extra_info)
  275. if 'extractor' not in ie_result:
  276. ie_result['extractor'] = ie.IE_NAME
  277. return self.process_ie_result(ie_result, download=download)
  278. except ExtractorError as de: # An error we somewhat expected
  279. self.report_error(compat_str(de), de.format_traceback())
  280. break
  281. except Exception as e:
  282. if self.params.get('ignoreerrors', False):
  283. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  284. break
  285. else:
  286. raise
  287. else:
  288. self.report_error(u'no suitable InfoExtractor: %s' % url)
  289. def process_ie_result(self, ie_result, download=True, extra_info={}):
  290. """
  291. Take the result of the ie(may be modified) and resolve all unresolved
  292. references (URLs, playlist items).
  293. It will also download the videos if 'download'.
  294. Returns the resolved ie_result.
  295. """
  296. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  297. if result_type == 'video':
  298. if 'playlist' not in ie_result:
  299. # It isn't part of a playlist
  300. ie_result['playlist'] = None
  301. ie_result['playlist_index'] = None
  302. if download:
  303. self.process_info(ie_result)
  304. return ie_result
  305. elif result_type == 'url':
  306. # We have to add extra_info to the results because it may be
  307. # contained in a playlist
  308. return self.extract_info(ie_result['url'],
  309. download,
  310. ie_key=ie_result.get('ie_key'),
  311. extra_info=extra_info)
  312. elif result_type == 'playlist':
  313. # We process each entry in the playlist
  314. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  315. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  316. playlist_results = []
  317. n_all_entries = len(ie_result['entries'])
  318. playliststart = self.params.get('playliststart', 1) - 1
  319. playlistend = self.params.get('playlistend', -1)
  320. if playlistend == -1:
  321. entries = ie_result['entries'][playliststart:]
  322. else:
  323. entries = ie_result['entries'][playliststart:playlistend]
  324. n_entries = len(entries)
  325. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  326. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  327. for i,entry in enumerate(entries,1):
  328. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  329. extra = {
  330. 'playlist': playlist,
  331. 'playlist_index': i + playliststart,
  332. }
  333. if not 'extractor' in entry:
  334. # We set the extractor, if it's an url it will be set then to
  335. # the new extractor, but if it's already a video we must make
  336. # sure it's present: see issue #877
  337. entry['extractor'] = ie_result['extractor']
  338. entry_result = self.process_ie_result(entry,
  339. download=download,
  340. extra_info=extra)
  341. playlist_results.append(entry_result)
  342. ie_result['entries'] = playlist_results
  343. return ie_result
  344. elif result_type == 'compat_list':
  345. def _fixup(r):
  346. r.setdefault('extractor', ie_result['extractor'])
  347. return r
  348. ie_result['entries'] = [
  349. self.process_ie_result(_fixup(r), download=download)
  350. for r in ie_result['entries']
  351. ]
  352. return ie_result
  353. else:
  354. raise Exception('Invalid result type: %s' % result_type)
  355. def process_info(self, info_dict):
  356. """Process a single resolved IE result."""
  357. assert info_dict.get('_type', 'video') == 'video'
  358. #We increment the download the download count here to match the previous behaviour.
  359. self.increment_downloads()
  360. info_dict['fulltitle'] = info_dict['title']
  361. if len(info_dict['title']) > 200:
  362. info_dict['title'] = info_dict['title'][:197] + u'...'
  363. # Keep for backwards compatibility
  364. info_dict['stitle'] = info_dict['title']
  365. if not 'format' in info_dict:
  366. info_dict['format'] = info_dict['ext']
  367. reason = self._match_entry(info_dict)
  368. if reason is not None:
  369. self.to_screen(u'[download] ' + reason)
  370. return
  371. max_downloads = self.params.get('max_downloads')
  372. if max_downloads is not None:
  373. if self._num_downloads > int(max_downloads):
  374. raise MaxDownloadsReached()
  375. filename = self.prepare_filename(info_dict)
  376. # Forced printings
  377. if self.params.get('forcetitle', False):
  378. compat_print(info_dict['title'])
  379. if self.params.get('forceid', False):
  380. compat_print(info_dict['id'])
  381. if self.params.get('forceurl', False):
  382. compat_print(info_dict['url'])
  383. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  384. compat_print(info_dict['thumbnail'])
  385. if self.params.get('forcedescription', False) and 'description' in info_dict:
  386. compat_print(info_dict['description'])
  387. if self.params.get('forcefilename', False) and filename is not None:
  388. compat_print(filename)
  389. if self.params.get('forceformat', False):
  390. compat_print(info_dict['format'])
  391. # Do nothing else if in simulate mode
  392. if self.params.get('simulate', False):
  393. return
  394. if filename is None:
  395. return
  396. try:
  397. dn = os.path.dirname(encodeFilename(filename))
  398. if dn != '' and not os.path.exists(dn):
  399. os.makedirs(dn)
  400. except (OSError, IOError) as err:
  401. self.report_error(u'unable to create directory ' + compat_str(err))
  402. return
  403. if self.params.get('writedescription', False):
  404. try:
  405. descfn = filename + u'.description'
  406. self.report_writedescription(descfn)
  407. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  408. descfile.write(info_dict['description'])
  409. except (OSError, IOError):
  410. self.report_error(u'Cannot write description file ' + descfn)
  411. return
  412. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  413. # subtitles download errors are already managed as troubles in relevant IE
  414. # that way it will silently go on when used with unsupporting IE
  415. subtitle = info_dict['subtitles'][0]
  416. (sub_error, sub_lang, sub) = subtitle
  417. sub_format = self.params.get('subtitlesformat')
  418. if sub_error:
  419. self.report_warning("Some error while getting the subtitles")
  420. else:
  421. try:
  422. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  423. self.report_writesubtitles(sub_filename)
  424. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  425. subfile.write(sub)
  426. except (OSError, IOError):
  427. self.report_error(u'Cannot write subtitles file ' + descfn)
  428. return
  429. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  430. subtitles = info_dict['subtitles']
  431. sub_format = self.params.get('subtitlesformat')
  432. for subtitle in subtitles:
  433. (sub_error, sub_lang, sub) = subtitle
  434. if sub_error:
  435. self.report_warning("Some error while getting the subtitles")
  436. else:
  437. try:
  438. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  439. self.report_writesubtitles(sub_filename)
  440. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  441. subfile.write(sub)
  442. except (OSError, IOError):
  443. self.report_error(u'Cannot write subtitles file ' + descfn)
  444. return
  445. if self.params.get('writeinfojson', False):
  446. infofn = filename + u'.info.json'
  447. self.report_writeinfojson(infofn)
  448. try:
  449. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  450. write_json_file(json_info_dict, encodeFilename(infofn))
  451. except (OSError, IOError):
  452. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  453. return
  454. if self.params.get('writethumbnail', False):
  455. if 'thumbnail' in info_dict:
  456. thumb_format = info_dict['thumbnail'].rpartition(u'/')[2].rpartition(u'.')[2]
  457. if not thumb_format:
  458. thumb_format = 'jpg'
  459. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  460. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  461. (info_dict['extractor'], info_dict['id']))
  462. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  463. with open(thumb_filename, 'wb') as thumbf:
  464. shutil.copyfileobj(uf, thumbf)
  465. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  466. (info_dict['extractor'], info_dict['id'], thumb_filename))
  467. if not self.params.get('skip_download', False):
  468. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  469. success = True
  470. else:
  471. try:
  472. success = self.fd._do_download(filename, info_dict)
  473. except (OSError, IOError) as err:
  474. raise UnavailableVideoError()
  475. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  476. self.report_error(u'unable to download video data: %s' % str(err))
  477. return
  478. except (ContentTooShortError, ) as err:
  479. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  480. return
  481. if success:
  482. try:
  483. self.post_process(filename, info_dict)
  484. except (PostProcessingError) as err:
  485. self.report_error(u'postprocessing: %s' % str(err))
  486. return
  487. def download(self, url_list):
  488. """Download a given list of URLs."""
  489. if len(url_list) > 1 and self.fixed_template():
  490. raise SameFileError(self.params['outtmpl'])
  491. for url in url_list:
  492. try:
  493. #It also downloads the videos
  494. videos = self.extract_info(url)
  495. except UnavailableVideoError:
  496. self.report_error(u'unable to download video')
  497. except MaxDownloadsReached:
  498. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  499. raise
  500. return self._download_retcode
  501. def post_process(self, filename, ie_info):
  502. """Run all the postprocessors on the given file."""
  503. info = dict(ie_info)
  504. info['filepath'] = filename
  505. keep_video = None
  506. for pp in self._pps:
  507. try:
  508. keep_video_wish,new_info = pp.run(info)
  509. if keep_video_wish is not None:
  510. if keep_video_wish:
  511. keep_video = keep_video_wish
  512. elif keep_video is None:
  513. # No clear decision yet, let IE decide
  514. keep_video = keep_video_wish
  515. except PostProcessingError as e:
  516. self.to_stderr(u'ERROR: ' + e.msg)
  517. if keep_video is False and not self.params.get('keepvideo', False):
  518. try:
  519. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  520. os.remove(encodeFilename(filename))
  521. except (IOError, OSError):
  522. self.report_warning(u'Unable to remove downloaded video file')