Commit b364bfe2 authored by Benjamin Peterson's avatar Benjamin Peterson

close the file even if an exception occurs #5536

parent 8ed25205
...@@ -233,41 +233,45 @@ class URLopener: ...@@ -233,41 +233,45 @@ class URLopener:
except IOError, msg: except IOError, msg:
pass pass
fp = self.open(url, data) fp = self.open(url, data)
headers = fp.info() try:
if filename: headers = fp.info()
tfp = open(filename, 'wb') if filename:
else: tfp = open(filename, 'wb')
import tempfile else:
garbage, path = splittype(url) import tempfile
garbage, path = splithost(path or "") garbage, path = splittype(url)
path, garbage = splitquery(path or "") garbage, path = splithost(path or "")
path, garbage = splitattr(path or "") path, garbage = splitquery(path or "")
suffix = os.path.splitext(path)[1] path, garbage = splitattr(path or "")
(fd, filename) = tempfile.mkstemp(suffix) suffix = os.path.splitext(path)[1]
self.__tempfiles.append(filename) (fd, filename) = tempfile.mkstemp(suffix)
tfp = os.fdopen(fd, 'wb') self.__tempfiles.append(filename)
result = filename, headers tfp = os.fdopen(fd, 'wb')
if self.tempcache is not None: try:
self.tempcache[url] = result result = filename, headers
bs = 1024*8 if self.tempcache is not None:
size = -1 self.tempcache[url] = result
read = 0 bs = 1024*8
blocknum = 0 size = -1
if reporthook: read = 0
if "content-length" in headers: blocknum = 0
size = int(headers["Content-Length"]) if reporthook:
reporthook(blocknum, bs, size) if "content-length" in headers:
while 1: size = int(headers["Content-Length"])
block = fp.read(bs) reporthook(blocknum, bs, size)
if block == "": while 1:
break block = fp.read(bs)
read += len(block) if block == "":
tfp.write(block) break
blocknum += 1 read += len(block)
if reporthook: tfp.write(block)
reporthook(blocknum, bs, size) blocknum += 1
fp.close() if reporthook:
tfp.close() reporthook(blocknum, bs, size)
finally:
tfp.close()
finally:
fp.close()
del fp del fp
del tfp del tfp
......
...@@ -188,6 +188,9 @@ Core and Builtins ...@@ -188,6 +188,9 @@ Core and Builtins
Library Library
------- -------
- Issue #5536: urllib.urlretrieve makes sure to close the file it's writing to
even if an exception occurs.
- Issue #5381: Added object_pairs_hook to the json module. This allows - Issue #5381: Added object_pairs_hook to the json module. This allows
OrderedDicts to be built by the decoder. OrderedDicts to be built by the decoder.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment