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