Commit 46ba6c85 authored by Serhiy Storchaka's avatar Serhiy Storchaka

Issue #22831: Use "with" to avoid possible fd leaks.

parent ae2d667a
...@@ -229,14 +229,13 @@ def binhex(inp, out): ...@@ -229,14 +229,13 @@ def binhex(inp, out):
finfo = getfileinfo(inp) finfo = getfileinfo(inp)
ofp = BinHex(finfo, out) ofp = BinHex(finfo, out)
ifp = io.open(inp, 'rb') with io.open(inp, 'rb') as ifp:
# XXXX Do textfile translation on non-mac systems # XXXX Do textfile translation on non-mac systems
while True: while True:
d = ifp.read(128000) d = ifp.read(128000)
if not d: break if not d: break
ofp.write(d) ofp.write(d)
ofp.close_data() ofp.close_data()
ifp.close()
ifp = openrsrc(inp, 'rb') ifp = openrsrc(inp, 'rb')
while True: while True:
...@@ -449,13 +448,12 @@ def hexbin(inp, out): ...@@ -449,13 +448,12 @@ def hexbin(inp, out):
if not out: if not out:
out = ifp.FName out = ifp.FName
ofp = io.open(out, 'wb') with io.open(out, 'wb') as ofp:
# XXXX Do translation on non-mac systems # XXXX Do translation on non-mac systems
while True: while True:
d = ifp.read(128000) d = ifp.read(128000)
if not d: break if not d: break
ofp.write(d) ofp.write(d)
ofp.close()
ifp.close_data() ifp.close_data()
d = ifp.read_rsrc(128000) d = ifp.read_rsrc(128000)
......
...@@ -294,9 +294,8 @@ class Hook: ...@@ -294,9 +294,8 @@ class Hook:
(fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir) (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
try: try:
file = os.fdopen(fd, 'w') with os.fdopen(fd, 'w') as file:
file.write(doc) file.write(doc)
file.close()
msg = '%s contains the description of this error.' % path msg = '%s contains the description of this error.' % path
except: except:
msg = 'Tried to save traceback to %s, but failed.' % path msg = 'Tried to save traceback to %s, but failed.' % path
......
...@@ -153,9 +153,9 @@ def whichdb(filename): ...@@ -153,9 +153,9 @@ def whichdb(filename):
except OSError: except OSError:
return None return None
with f:
# Read the start of the file -- the magic number # Read the start of the file -- the magic number
s16 = f.read(16) s16 = f.read(16)
f.close()
s = s16[0:4] s = s16[0:4]
# Return "" if not at least 4 bytes # Return "" if not at least 4 bytes
......
...@@ -1999,7 +1999,6 @@ class MozillaCookieJar(FileCookieJar): ...@@ -1999,7 +1999,6 @@ class MozillaCookieJar(FileCookieJar):
magic = f.readline() magic = f.readline()
if not self.magic_re.search(magic): if not self.magic_re.search(magic):
f.close()
raise LoadError( raise LoadError(
"%r does not look like a Netscape format cookies file" % "%r does not look like a Netscape format cookies file" %
filename) filename)
......
...@@ -163,7 +163,7 @@ def libc_ver(executable=sys.executable, lib='', version='', ...@@ -163,7 +163,7 @@ def libc_ver(executable=sys.executable, lib='', version='',
# here to work around problems with Cygwin not being # here to work around problems with Cygwin not being
# able to open symlinks for reading # able to open symlinks for reading
executable = os.path.realpath(executable) executable = os.path.realpath(executable)
f = open(executable, 'rb') with open(executable, 'rb') as f:
binary = f.read(chunksize) binary = f.read(chunksize)
pos = 0 pos = 0
while 1: while 1:
...@@ -196,7 +196,6 @@ def libc_ver(executable=sys.executable, lib='', version='', ...@@ -196,7 +196,6 @@ def libc_ver(executable=sys.executable, lib='', version='',
if threads and version[-len(threads):] != threads: if threads and version[-len(threads):] != threads:
version = version + threads version = version + threads
pos = m.end() pos = m.end()
f.close()
return lib, version return lib, version
def _dist_try_harder(distname, version, id): def _dist_try_harder(distname, version, id):
......
...@@ -1639,9 +1639,8 @@ def writedoc(thing, forceload=0): ...@@ -1639,9 +1639,8 @@ def writedoc(thing, forceload=0):
try: try:
object, name = resolve(thing, forceload) object, name = resolve(thing, forceload)
page = html.page(describe(object), html.document(object, name)) page = html.page(describe(object), html.document(object, name))
file = open(name + '.html', 'w', encoding='utf-8') with open(name + '.html', 'w', encoding='utf-8') as file:
file.write(page) file.write(page)
file.close()
print('wrote', name + '.html') print('wrote', name + '.html')
except (ImportError, ErrorDuringImport) as value: except (ImportError, ErrorDuringImport) as value:
print(value) print(value)
......
...@@ -182,7 +182,7 @@ if __name__ == "__main__": ...@@ -182,7 +182,7 @@ if __name__ == "__main__":
items = sorted(d) items = sorted(d)
for item in items: for item in items:
f.write("#define %s_%s %d\n" % (prefix, item, item)) f.write("#define %s_%s %d\n" % (prefix, item, item))
f = open("sre_constants.h", "w") with open("sre_constants.h", "w") as f:
f.write("""\ f.write("""\
/* /*
* Secret Labs' Regular Expression Engine * Secret Labs' Regular Expression Engine
...@@ -219,5 +219,4 @@ if __name__ == "__main__": ...@@ -219,5 +219,4 @@ if __name__ == "__main__":
f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL) f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL)
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET) f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
f.close()
print("done") print("done")
...@@ -97,8 +97,8 @@ def _main(): ...@@ -97,8 +97,8 @@ def _main():
except OSError as err: except OSError as err:
sys.stdout.write("I/O error: %s\n" % str(err)) sys.stdout.write("I/O error: %s\n" % str(err))
sys.exit(1) sys.exit(1)
with fp:
lines = fp.read().split("\n") lines = fp.read().split("\n")
fp.close()
prog = re.compile( prog = re.compile(
"#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)", "#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)",
re.IGNORECASE) re.IGNORECASE)
...@@ -116,8 +116,8 @@ def _main(): ...@@ -116,8 +116,8 @@ def _main():
except OSError as err: except OSError as err:
sys.stderr.write("I/O error: %s\n" % str(err)) sys.stderr.write("I/O error: %s\n" % str(err))
sys.exit(2) sys.exit(2)
with fp:
format = fp.read().split("\n") format = fp.read().split("\n")
fp.close()
try: try:
start = format.index("#--start constants--") + 1 start = format.index("#--start constants--") + 1
end = format.index("#--end constants--") end = format.index("#--end constants--")
...@@ -133,8 +133,8 @@ def _main(): ...@@ -133,8 +133,8 @@ def _main():
except OSError as err: except OSError as err:
sys.stderr.write("I/O error: %s\n" % str(err)) sys.stderr.write("I/O error: %s\n" % str(err))
sys.exit(4) sys.exit(4)
with fp:
fp.write("\n".join(format)) fp.write("\n".join(format))
fp.close()
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -232,8 +232,8 @@ class CoverageResults: ...@@ -232,8 +232,8 @@ class CoverageResults:
if self.infile: if self.infile:
# Try to merge existing counts file. # Try to merge existing counts file.
try: try:
counts, calledfuncs, callers = \ with open(self.infile, 'rb') as f:
pickle.load(open(self.infile, 'rb')) counts, calledfuncs, callers = pickle.load(f)
self.update(self.__class__(counts, calledfuncs, callers)) self.update(self.__class__(counts, calledfuncs, callers))
except (OSError, EOFError, ValueError) as err: except (OSError, EOFError, ValueError) as err:
print(("Skipping counts file %r: %s" print(("Skipping counts file %r: %s"
...@@ -361,6 +361,7 @@ class CoverageResults: ...@@ -361,6 +361,7 @@ class CoverageResults:
n_lines = 0 n_lines = 0
n_hits = 0 n_hits = 0
with outfile:
for lineno, line in enumerate(lines, 1): for lineno, line in enumerate(lines, 1):
# do the blank/comment match to try to mark more lines # do the blank/comment match to try to mark more lines
# (help the reader find stuff that hasn't been covered) # (help the reader find stuff that hasn't been covered)
...@@ -380,7 +381,6 @@ class CoverageResults: ...@@ -380,7 +381,6 @@ class CoverageResults:
else: else:
outfile.write(" ") outfile.write(" ")
outfile.write(line.expandtabs(8)) outfile.write(line.expandtabs(8))
outfile.close()
return n_hits, n_lines return n_hits, n_lines
......
...@@ -1010,12 +1010,9 @@ def gzip_encode(data): ...@@ -1010,12 +1010,9 @@ def gzip_encode(data):
if not gzip: if not gzip:
raise NotImplementedError raise NotImplementedError
f = BytesIO() f = BytesIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf:
gzf.write(data) gzf.write(data)
gzf.close() return f.getvalue()
encoded = f.getvalue()
f.close()
return encoded
## ##
# Decode a string using the gzip content encoding such as specified by the # Decode a string using the gzip content encoding such as specified by the
...@@ -1036,8 +1033,7 @@ def gzip_decode(data, max_decode=20971520): ...@@ -1036,8 +1033,7 @@ def gzip_decode(data, max_decode=20971520):
""" """
if not gzip: if not gzip:
raise NotImplementedError raise NotImplementedError
f = BytesIO(data) with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf:
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try: try:
if max_decode < 0: # no limit if max_decode < 0: # no limit
decoded = gzf.read() decoded = gzf.read()
...@@ -1045,8 +1041,6 @@ def gzip_decode(data, max_decode=20971520): ...@@ -1045,8 +1041,6 @@ def gzip_decode(data, max_decode=20971520):
decoded = gzf.read(max_decode + 1) decoded = gzf.read(max_decode + 1)
except OSError: except OSError:
raise ValueError("invalid data") raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode: if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded") raise ValueError("max gzipped payload length exceeded")
return decoded return decoded
......
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