Merged revisions 70521 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r70521 | benjamin.peterson | 2009-03-22 12:45:11 -0500 (Sun, 22 Mar 2009) | 1 line

  close the file even if an exception occurs #5536
........
This commit is contained in:
Benjamin Peterson 2009-03-22 17:49:21 +00:00
parent 218f462a0f
commit 373498fc67
2 changed files with 42 additions and 35 deletions

View File

@ -233,41 +233,45 @@ class URLopener:
except IOError, msg:
pass
fp = self.open(url, data)
headers = fp.info()
if filename:
tfp = open(filename, 'wb')
else:
import tempfile
garbage, path = splittype(url)
garbage, path = splithost(path or "")
path, garbage = splitquery(path or "")
path, garbage = splitattr(path or "")
suffix = os.path.splitext(path)[1]
(fd, filename) = tempfile.mkstemp(suffix)
self.__tempfiles.append(filename)
tfp = os.fdopen(fd, 'wb')
result = filename, headers
if self.tempcache is not None:
self.tempcache[url] = result
bs = 1024*8
size = -1
read = 0
blocknum = 0
if reporthook:
if "content-length" in headers:
size = int(headers["Content-Length"])
reporthook(blocknum, bs, size)
while 1:
block = fp.read(bs)
if block == "":
break
read += len(block)
tfp.write(block)
blocknum += 1
if reporthook:
reporthook(blocknum, bs, size)
fp.close()
tfp.close()
try:
headers = fp.info()
if filename:
tfp = open(filename, 'wb')
else:
import tempfile
garbage, path = splittype(url)
garbage, path = splithost(path or "")
path, garbage = splitquery(path or "")
path, garbage = splitattr(path or "")
suffix = os.path.splitext(path)[1]
(fd, filename) = tempfile.mkstemp(suffix)
self.__tempfiles.append(filename)
tfp = os.fdopen(fd, 'wb')
try:
result = filename, headers
if self.tempcache is not None:
self.tempcache[url] = result
bs = 1024*8
size = -1
read = 0
blocknum = 0
if reporthook:
if "content-length" in headers:
size = int(headers["Content-Length"])
reporthook(blocknum, bs, size)
while 1:
block = fp.read(bs)
if block == "":
break
read += len(block)
tfp.write(block)
blocknum += 1
if reporthook:
reporthook(blocknum, bs, size)
finally:
tfp.close()
finally:
fp.close()
del fp
del tfp

View File

@ -92,6 +92,9 @@ Core and Builtins
Library
-------
- Issue #5536: urllib.urlretrieve makes sure to close the file it's writing to
even if an exception occurs.
- Fix Decimal.__format__ bug that swapped the meanings of the '<' and
'>' alignment characters.