Skip to content

Commit 46ba6c8

Browse files
committedApr 4, 2015
Issue python#22831: Use "with" to avoid possible fd leaks.
1 parent ae2d667 commit 46ba6c8

10 files changed

+107
-120
lines changed
 

‎Lib/binhex.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -229,14 +229,13 @@ def binhex(inp, out):
229229
finfo = getfileinfo(inp)
230230
ofp = BinHex(finfo, out)
231231

232-
ifp = io.open(inp, 'rb')
233-
# XXXX Do textfile translation on non-mac systems
234-
while True:
235-
d = ifp.read(128000)
236-
if not d: break
237-
ofp.write(d)
238-
ofp.close_data()
239-
ifp.close()
232+
with io.open(inp, 'rb') as ifp:
233+
# XXXX Do textfile translation on non-mac systems
234+
while True:
235+
d = ifp.read(128000)
236+
if not d: break
237+
ofp.write(d)
238+
ofp.close_data()
240239

241240
ifp = openrsrc(inp, 'rb')
242241
while True:
@@ -449,13 +448,12 @@ def hexbin(inp, out):
449448
if not out:
450449
out = ifp.FName
451450

452-
ofp = io.open(out, 'wb')
453-
# XXXX Do translation on non-mac systems
454-
while True:
455-
d = ifp.read(128000)
456-
if not d: break
457-
ofp.write(d)
458-
ofp.close()
451+
with io.open(out, 'wb') as ofp:
452+
# XXXX Do translation on non-mac systems
453+
while True:
454+
d = ifp.read(128000)
455+
if not d: break
456+
ofp.write(d)
459457
ifp.close_data()
460458

461459
d = ifp.read_rsrc(128000)

‎Lib/cgitb.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -294,9 +294,8 @@ def handle(self, info=None):
294294
(fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
295295

296296
try:
297-
file = os.fdopen(fd, 'w')
298-
file.write(doc)
299-
file.close()
297+
with os.fdopen(fd, 'w') as file:
298+
file.write(doc)
300299
msg = '%s contains the description of this error.' % path
301300
except:
302301
msg = 'Tried to save traceback to %s, but failed.' % path

‎Lib/dbm/__init__.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,9 @@ def whichdb(filename):
153153
except OSError:
154154
return None
155155

156-
# Read the start of the file -- the magic number
157-
s16 = f.read(16)
158-
f.close()
156+
with f:
157+
# Read the start of the file -- the magic number
158+
s16 = f.read(16)
159159
s = s16[0:4]
160160

161161
# Return "" if not at least 4 bytes

‎Lib/http/cookiejar.py

-1
Original file line numberDiff line numberDiff line change
@@ -1999,7 +1999,6 @@ def _really_load(self, f, filename, ignore_discard, ignore_expires):
19991999

20002000
magic = f.readline()
20012001
if not self.magic_re.search(magic):
2002-
f.close()
20032002
raise LoadError(
20042003
"%r does not look like a Netscape format cookies file" %
20052004
filename)

‎Lib/platform.py

+32-33
Original file line numberDiff line numberDiff line change
@@ -163,40 +163,39 @@ def libc_ver(executable=sys.executable, lib='', version='',
163163
# here to work around problems with Cygwin not being
164164
# able to open symlinks for reading
165165
executable = os.path.realpath(executable)
166-
f = open(executable, 'rb')
167-
binary = f.read(chunksize)
168-
pos = 0
169-
while 1:
170-
if b'libc' in binary or b'GLIBC' in binary:
171-
m = _libc_search.search(binary, pos)
172-
else:
173-
m = None
174-
if not m:
175-
binary = f.read(chunksize)
176-
if not binary:
177-
break
178-
pos = 0
179-
continue
180-
libcinit, glibc, glibcversion, so, threads, soversion = [
181-
s.decode('latin1') if s is not None else s
182-
for s in m.groups()]
183-
if libcinit and not lib:
184-
lib = 'libc'
185-
elif glibc:
186-
if lib != 'glibc':
187-
lib = 'glibc'
188-
version = glibcversion
189-
elif glibcversion > version:
190-
version = glibcversion
191-
elif so:
192-
if lib != 'glibc':
166+
with open(executable, 'rb') as f:
167+
binary = f.read(chunksize)
168+
pos = 0
169+
while 1:
170+
if b'libc' in binary or b'GLIBC' in binary:
171+
m = _libc_search.search(binary, pos)
172+
else:
173+
m = None
174+
if not m:
175+
binary = f.read(chunksize)
176+
if not binary:
177+
break
178+
pos = 0
179+
continue
180+
libcinit, glibc, glibcversion, so, threads, soversion = [
181+
s.decode('latin1') if s is not None else s
182+
for s in m.groups()]
183+
if libcinit and not lib:
193184
lib = 'libc'
194-
if soversion and soversion > version:
195-
version = soversion
196-
if threads and version[-len(threads):] != threads:
197-
version = version + threads
198-
pos = m.end()
199-
f.close()
185+
elif glibc:
186+
if lib != 'glibc':
187+
lib = 'glibc'
188+
version = glibcversion
189+
elif glibcversion > version:
190+
version = glibcversion
191+
elif so:
192+
if lib != 'glibc':
193+
lib = 'libc'
194+
if soversion and soversion > version:
195+
version = soversion
196+
if threads and version[-len(threads):] != threads:
197+
version = version + threads
198+
pos = m.end()
200199
return lib, version
201200

202201
def _dist_try_harder(distname, version, id):

‎Lib/pydoc.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1639,9 +1639,8 @@ def writedoc(thing, forceload=0):
16391639
try:
16401640
object, name = resolve(thing, forceload)
16411641
page = html.page(describe(object), html.document(object, name))
1642-
file = open(name + '.html', 'w', encoding='utf-8')
1643-
file.write(page)
1644-
file.close()
1642+
with open(name + '.html', 'w', encoding='utf-8') as file:
1643+
file.write(page)
16451644
print('wrote', name + '.html')
16461645
except (ImportError, ErrorDuringImport) as value:
16471646
print(value)

‎Lib/sre_constants.py

+18-19
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def dump(f, d, prefix):
182182
items = sorted(d)
183183
for item in items:
184184
f.write("#define %s_%s %d\n" % (prefix, item, item))
185-
f = open("sre_constants.h", "w")
186-
f.write("""\
185+
with open("sre_constants.h", "w") as f:
186+
f.write("""\
187187
/*
188188
* Secret Labs' Regular Expression Engine
189189
*
@@ -199,25 +199,24 @@ def dump(f, d, prefix):
199199
200200
""")
201201

202-
f.write("#define SRE_MAGIC %d\n" % MAGIC)
202+
f.write("#define SRE_MAGIC %d\n" % MAGIC)
203203

204-
dump(f, OPCODES, "SRE_OP")
205-
dump(f, ATCODES, "SRE")
206-
dump(f, CHCODES, "SRE")
204+
dump(f, OPCODES, "SRE_OP")
205+
dump(f, ATCODES, "SRE")
206+
dump(f, CHCODES, "SRE")
207207

208-
f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE)
209-
f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE)
210-
f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE)
211-
f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE)
212-
f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL)
213-
f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE)
214-
f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE)
215-
f.write("#define SRE_FLAG_DEBUG %d\n" % SRE_FLAG_DEBUG)
216-
f.write("#define SRE_FLAG_ASCII %d\n" % SRE_FLAG_ASCII)
208+
f.write("#define SRE_FLAG_TEMPLATE %d\n" % SRE_FLAG_TEMPLATE)
209+
f.write("#define SRE_FLAG_IGNORECASE %d\n" % SRE_FLAG_IGNORECASE)
210+
f.write("#define SRE_FLAG_LOCALE %d\n" % SRE_FLAG_LOCALE)
211+
f.write("#define SRE_FLAG_MULTILINE %d\n" % SRE_FLAG_MULTILINE)
212+
f.write("#define SRE_FLAG_DOTALL %d\n" % SRE_FLAG_DOTALL)
213+
f.write("#define SRE_FLAG_UNICODE %d\n" % SRE_FLAG_UNICODE)
214+
f.write("#define SRE_FLAG_VERBOSE %d\n" % SRE_FLAG_VERBOSE)
215+
f.write("#define SRE_FLAG_DEBUG %d\n" % SRE_FLAG_DEBUG)
216+
f.write("#define SRE_FLAG_ASCII %d\n" % SRE_FLAG_ASCII)
217217

218-
f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX)
219-
f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL)
220-
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
218+
f.write("#define SRE_INFO_PREFIX %d\n" % SRE_INFO_PREFIX)
219+
f.write("#define SRE_INFO_LITERAL %d\n" % SRE_INFO_LITERAL)
220+
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
221221

222-
f.close()
223222
print("done")

‎Lib/token.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,8 @@ def _main():
9797
except OSError as err:
9898
sys.stdout.write("I/O error: %s\n" % str(err))
9999
sys.exit(1)
100-
lines = fp.read().split("\n")
101-
fp.close()
100+
with fp:
101+
lines = fp.read().split("\n")
102102
prog = re.compile(
103103
"#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)",
104104
re.IGNORECASE)
@@ -116,8 +116,8 @@ def _main():
116116
except OSError as err:
117117
sys.stderr.write("I/O error: %s\n" % str(err))
118118
sys.exit(2)
119-
format = fp.read().split("\n")
120-
fp.close()
119+
with fp:
120+
format = fp.read().split("\n")
121121
try:
122122
start = format.index("#--start constants--") + 1
123123
end = format.index("#--end constants--")
@@ -133,8 +133,8 @@ def _main():
133133
except OSError as err:
134134
sys.stderr.write("I/O error: %s\n" % str(err))
135135
sys.exit(4)
136-
fp.write("\n".join(format))
137-
fp.close()
136+
with fp:
137+
fp.write("\n".join(format))
138138

139139

140140
if __name__ == "__main__":

‎Lib/trace.py

+20-20
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,8 @@ def __init__(self, counts=None, calledfuncs=None, infile=None,
232232
if self.infile:
233233
# Try to merge existing counts file.
234234
try:
235-
counts, calledfuncs, callers = \
236-
pickle.load(open(self.infile, 'rb'))
235+
with open(self.infile, 'rb') as f:
236+
counts, calledfuncs, callers = pickle.load(f)
237237
self.update(self.__class__(counts, calledfuncs, callers))
238238
except (OSError, EOFError, ValueError) as err:
239239
print(("Skipping counts file %r: %s"
@@ -361,26 +361,26 @@ def write_results_file(self, path, lines, lnotab, lines_hit, encoding=None):
361361

362362
n_lines = 0
363363
n_hits = 0
364-
for lineno, line in enumerate(lines, 1):
365-
# do the blank/comment match to try to mark more lines
366-
# (help the reader find stuff that hasn't been covered)
367-
if lineno in lines_hit:
368-
outfile.write("%5d: " % lines_hit[lineno])
369-
n_hits += 1
370-
n_lines += 1
371-
elif rx_blank.match(line):
372-
outfile.write(" ")
373-
else:
374-
# lines preceded by no marks weren't hit
375-
# Highlight them if so indicated, unless the line contains
376-
# #pragma: NO COVER
377-
if lineno in lnotab and not PRAGMA_NOCOVER in line:
378-
outfile.write(">>>>>> ")
364+
with outfile:
365+
for lineno, line in enumerate(lines, 1):
366+
# do the blank/comment match to try to mark more lines
367+
# (help the reader find stuff that hasn't been covered)
368+
if lineno in lines_hit:
369+
outfile.write("%5d: " % lines_hit[lineno])
370+
n_hits += 1
379371
n_lines += 1
380-
else:
372+
elif rx_blank.match(line):
381373
outfile.write(" ")
382-
outfile.write(line.expandtabs(8))
383-
outfile.close()
374+
else:
375+
# lines preceded by no marks weren't hit
376+
# Highlight them if so indicated, unless the line contains
377+
# #pragma: NO COVER
378+
if lineno in lnotab and not PRAGMA_NOCOVER in line:
379+
outfile.write(">>>>>> ")
380+
n_lines += 1
381+
else:
382+
outfile.write(" ")
383+
outfile.write(line.expandtabs(8))
384384

385385
return n_hits, n_lines
386386

‎Lib/xmlrpc/client.py

+11-17
Original file line numberDiff line numberDiff line change
@@ -1010,12 +1010,9 @@ def gzip_encode(data):
10101010
if not gzip:
10111011
raise NotImplementedError
10121012
f = BytesIO()
1013-
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
1014-
gzf.write(data)
1015-
gzf.close()
1016-
encoded = f.getvalue()
1017-
f.close()
1018-
return encoded
1013+
with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf:
1014+
gzf.write(data)
1015+
return f.getvalue()
10191016

10201017
##
10211018
# Decode a string using the gzip content encoding such as specified by the
@@ -1036,17 +1033,14 @@ def gzip_decode(data, max_decode=20971520):
10361033
"""
10371034
if not gzip:
10381035
raise NotImplementedError
1039-
f = BytesIO(data)
1040-
gzf = gzip.GzipFile(mode="rb", fileobj=f)
1041-
try:
1042-
if max_decode < 0: # no limit
1043-
decoded = gzf.read()
1044-
else:
1045-
decoded = gzf.read(max_decode + 1)
1046-
except OSError:
1047-
raise ValueError("invalid data")
1048-
f.close()
1049-
gzf.close()
1036+
with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf:
1037+
try:
1038+
if max_decode < 0: # no limit
1039+
decoded = gzf.read()
1040+
else:
1041+
decoded = gzf.read(max_decode + 1)
1042+
except OSError:
1043+
raise ValueError("invalid data")
10501044
if max_decode >= 0 and len(decoded) > max_decode:
10511045
raise ValueError("max gzipped payload length exceeded")
10521046
return decoded

0 commit comments

Comments
 (0)