summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2009-03-22 17:45:11 (GMT)
committerBenjamin Peterson <benjamin@python.org>2009-03-22 17:45:11 (GMT)
commitb364bfe2f406a99a83fc5b1073726ecbaa63f50f (patch)
tree629b0ca3ca59e84714cf0833bacf0d5a16aef60b /Lib
parent8ed252053658fb0375e1db0346c479b76b6d3c62 (diff)
downloadcpython-b364bfe2f406a99a83fc5b1073726ecbaa63f50f.zip
cpython-b364bfe2f406a99a83fc5b1073726ecbaa63f50f.tar.gz
cpython-b364bfe2f406a99a83fc5b1073726ecbaa63f50f.tar.bz2
close the file even if an exception occurs #5536
Diffstat (limited to 'Lib')
-rw-r--r--Lib/urllib.py74
1 files changed, 39 insertions, 35 deletions
diff --git a/Lib/urllib.py b/Lib/urllib.py
index d23d070..0594dc8 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -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