Skip to content

Commit 172bb39

Browse files
bpo-22831: Use "with" to avoid possible fd leaks in tools (part 2). (GH-10927)
1 parent afbb7a3 commit 172bb39

27 files changed

+248
-258
lines changed

Tools/demo/markov.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,9 @@ def test():
7878
continue
7979
else:
8080
f = open(filename, 'r')
81-
if debug: print('processing', filename, '...')
82-
text = f.read()
83-
f.close()
81+
with f:
82+
if debug: print('processing', filename, '...')
83+
text = f.read()
8484
paralist = text.split('\n\n')
8585
for para in paralist:
8686
if debug > 1: print('feeding ...')

Tools/demo/rpython.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,16 @@ def main():
2222
port = int(port[i+1:])
2323
host = host[:i]
2424
command = ' '.join(sys.argv[2:])
25-
s = socket(AF_INET, SOCK_STREAM)
26-
s.connect((host, port))
27-
s.send(command.encode())
28-
s.shutdown(SHUT_WR)
29-
reply = b''
30-
while True:
31-
data = s.recv(BUFSIZE)
32-
if not data:
33-
break
34-
reply += data
35-
print(reply.decode(), end=' ')
36-
s.close()
25+
with socket(AF_INET, SOCK_STREAM) as s:
26+
s.connect((host, port))
27+
s.send(command.encode())
28+
s.shutdown(SHUT_WR)
29+
reply = b''
30+
while True:
31+
data = s.recv(BUFSIZE)
32+
if not data:
33+
break
34+
reply += data
35+
print(reply.decode(), end=' ')
3736

3837
main()

Tools/demo/rpythond.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,16 @@ def main():
2626
s.listen(1)
2727
while True:
2828
conn, (remotehost, remoteport) = s.accept()
29-
print('connection from', remotehost, remoteport)
30-
request = b''
31-
while 1:
32-
data = conn.recv(BUFSIZE)
33-
if not data:
34-
break
35-
request += data
36-
reply = execute(request.decode())
37-
conn.send(reply.encode())
38-
conn.close()
29+
with conn:
30+
print('connection from', remotehost, remoteport)
31+
request = b''
32+
while 1:
33+
data = conn.recv(BUFSIZE)
34+
if not data:
35+
break
36+
request += data
37+
reply = execute(request.decode())
38+
conn.send(reply.encode())
3939

4040
def execute(request):
4141
stdout = sys.stdout

Tools/freeze/checkextensions_win32.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,8 @@ def parse_dsp(dsp):
130130
ret = []
131131
dsp_path, dsp_name = os.path.split(dsp)
132132
try:
133-
lines = open(dsp, "r").readlines()
133+
with open(dsp, "r") as fp:
134+
lines = fp.readlines()
134135
except IOError as msg:
135136
sys.stderr.write("%s: %s\n" % (dsp, msg))
136137
return None

Tools/freeze/freeze.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ def main():
142142
# last option can not be "-i", so this ensures "pos+1" is in range!
143143
if sys.argv[pos] == '-i':
144144
try:
145-
options = open(sys.argv[pos+1]).read().split()
145+
with open(sys.argv[pos+1]) as infp:
146+
options = infp.read().split()
146147
except IOError as why:
147148
usage("File name '%s' specified with the -i option "
148149
"can not be read - %s" % (sys.argv[pos+1], why) )

Tools/i18n/pygettext.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -561,9 +561,8 @@ class Options:
561561
# initialize list of strings to exclude
562562
if options.excludefilename:
563563
try:
564-
fp = open(options.excludefilename)
565-
options.toexclude = fp.readlines()
566-
fp.close()
564+
with open(options.excludefilename) as fp:
565+
options.toexclude = fp.readlines()
567566
except IOError:
568567
print(_(
569568
"Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)

Tools/scripts/cleanfuture.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,11 @@ def check(file):
9696
errprint("%r: I/O Error: %s" % (file, str(msg)))
9797
return
9898

99-
ff = FutureFinder(f, file)
100-
changed = ff.run()
101-
if changed:
102-
ff.gettherest()
103-
f.close()
99+
with f:
100+
ff = FutureFinder(f, file)
101+
changed = ff.run()
102+
if changed:
103+
ff.gettherest()
104104
if changed:
105105
if verbose:
106106
print("changed.")
@@ -122,9 +122,8 @@ def check(file):
122122
os.rename(file, bak)
123123
if verbose:
124124
print("renamed", file, "to", bak)
125-
g = open(file, "w")
126-
ff.write(g)
127-
g.close()
125+
with open(file, "w") as g:
126+
ff.write(g)
128127
if verbose:
129128
print("wrote new", file)
130129
else:

Tools/scripts/combinerefs.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,7 @@ def read(fileiter, pat, whilematch):
8585
else:
8686
break
8787

88-
def combine(fname):
89-
f = open(fname)
90-
88+
def combinefile(f):
9189
fi = iter(f)
9290

9391
for line in read(fi, re.compile(r'^Remaining objects:$'), False):
@@ -121,8 +119,11 @@ def combine(fname):
121119
print('[%s->%s]' % (addr2rc[addr], rc), end=' ')
122120
print(guts, addr2guts[addr])
123121

124-
f.close()
125122
print("%d objects before, %d after" % (before, after))
126123

124+
def combine(fname):
125+
with open(fname) as f:
126+
combinefile(f)
127+
127128
if __name__ == '__main__':
128129
combine(sys.argv[1])

Tools/scripts/dutree.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,18 @@
44
import os, sys, errno
55

66
def main():
7-
p = os.popen('du ' + ' '.join(sys.argv[1:]), 'r')
87
total, d = None, {}
9-
for line in p.readlines():
10-
i = 0
11-
while line[i] in '0123456789': i = i+1
12-
size = eval(line[:i])
13-
while line[i] in ' \t': i = i+1
14-
filename = line[i:-1]
15-
comps = filename.split('/')
16-
if comps[0] == '': comps[0] = '/'
17-
if comps[len(comps)-1] == '': del comps[len(comps)-1]
18-
total, d = store(size, comps, total, d)
8+
with os.popen('du ' + ' '.join(sys.argv[1:])) as p:
9+
for line in p:
10+
i = 0
11+
while line[i] in '0123456789': i = i+1
12+
size = eval(line[:i])
13+
while line[i] in ' \t': i = i+1
14+
filename = line[i:-1]
15+
comps = filename.split('/')
16+
if comps[0] == '': comps[0] = '/'
17+
if comps[len(comps)-1] == '': del comps[len(comps)-1]
18+
total, d = store(size, comps, total, d)
1919
try:
2020
display(total, d)
2121
except IOError as e:

Tools/scripts/eptags.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,29 +28,30 @@ def treat_file(filename, outfp):
2828
except OSError:
2929
sys.stderr.write('Cannot open %s\n'%filename)
3030
return
31-
charno = 0
32-
lineno = 0
33-
tags = []
34-
size = 0
35-
while 1:
36-
line = fp.readline()
37-
if not line:
38-
break
39-
lineno = lineno + 1
40-
m = matcher.search(line)
41-
if m:
42-
tag = m.group(0) + '\177%d,%d\n' % (lineno, charno)
43-
tags.append(tag)
44-
size = size + len(tag)
45-
charno = charno + len(line)
31+
with fp:
32+
charno = 0
33+
lineno = 0
34+
tags = []
35+
size = 0
36+
while 1:
37+
line = fp.readline()
38+
if not line:
39+
break
40+
lineno = lineno + 1
41+
m = matcher.search(line)
42+
if m:
43+
tag = m.group(0) + '\177%d,%d\n' % (lineno, charno)
44+
tags.append(tag)
45+
size = size + len(tag)
46+
charno = charno + len(line)
4647
outfp.write('\f\n%s,%d\n' % (filename,size))
4748
for tag in tags:
4849
outfp.write(tag)
4950

5051
def main():
51-
outfp = open('TAGS', 'w')
52-
for filename in sys.argv[1:]:
53-
treat_file(filename, outfp)
52+
with open('TAGS', 'w') as outfp:
53+
for filename in sys.argv[1:]:
54+
treat_file(filename, outfp)
5455

5556
if __name__=="__main__":
5657
main()

Tools/scripts/finddiv.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,17 @@ def process(filename, listnames):
5555
except IOError as msg:
5656
sys.stderr.write("Can't open: %s\n" % msg)
5757
return 1
58-
g = tokenize.generate_tokens(fp.readline)
59-
lastrow = None
60-
for type, token, (row, col), end, line in g:
61-
if token in ("/", "/="):
62-
if listnames:
63-
print(filename)
64-
break
65-
if row != lastrow:
66-
lastrow = row
67-
print("%s:%d:%s" % (filename, row, line), end=' ')
68-
fp.close()
58+
with fp:
59+
g = tokenize.generate_tokens(fp.readline)
60+
lastrow = None
61+
for type, token, (row, col), end, line in g:
62+
if token in ("/", "/="):
63+
if listnames:
64+
print(filename)
65+
break
66+
if row != lastrow:
67+
lastrow = row
68+
print("%s:%d:%s" % (filename, row, line), end=' ')
6969

7070
def processdir(dir, listnames):
7171
try:

Tools/scripts/fixnotice.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -73,22 +73,19 @@ def main():
7373
elif opt == '--dry-run':
7474
DRYRUN = 1
7575
elif opt == '--oldnotice':
76-
fp = open(arg)
77-
OLD_NOTICE = fp.read()
78-
fp.close()
76+
with open(arg) as fp:
77+
OLD_NOTICE = fp.read()
7978
elif opt == '--newnotice':
80-
fp = open(arg)
81-
NEW_NOTICE = fp.read()
82-
fp.close()
79+
with open(arg) as fp:
80+
NEW_NOTICE = fp.read()
8381

8482
for arg in args:
8583
process(arg)
8684

8785

8886
def process(file):
89-
f = open(file)
90-
data = f.read()
91-
f.close()
87+
with open(file) as f:
88+
data = f.read()
9289
i = data.find(OLD_NOTICE)
9390
if i < 0:
9491
if VERBOSE:
@@ -102,9 +99,8 @@ def process(file):
10299
data = data[:i] + NEW_NOTICE + data[i+len(OLD_NOTICE):]
103100
new = file + ".new"
104101
backup = file + ".bak"
105-
f = open(new, "w")
106-
f.write(data)
107-
f.close()
102+
with open(new, "w") as f:
103+
f.write(data)
108104
os.rename(file, backup)
109105
os.rename(new, file)
110106

Tools/scripts/fixps.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,18 @@ def main():
1414
except IOError as msg:
1515
print(filename, ': can\'t open :', msg)
1616
continue
17-
line = f.readline()
18-
if not re.match('^#! */usr/local/bin/python', line):
19-
print(filename, ': not a /usr/local/bin/python script')
20-
f.close()
21-
continue
22-
rest = f.read()
23-
f.close()
17+
with f:
18+
line = f.readline()
19+
if not re.match('^#! */usr/local/bin/python', line):
20+
print(filename, ': not a /usr/local/bin/python script')
21+
continue
22+
rest = f.read()
2423
line = re.sub('/usr/local/bin/python',
2524
'/usr/bin/env python', line)
2625
print(filename, ':', repr(line))
27-
f = open(filename, "w")
28-
f.write(line)
29-
f.write(rest)
30-
f.close()
26+
with open(filename, "w") as f:
27+
f.write(line)
28+
f.write(rest)
3129

3230
if __name__ == '__main__':
3331
main()

Tools/scripts/get-remote-certificate.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,29 +29,26 @@ def strip_to_x509_cert(certfile_contents, outfile=None):
2929
return None
3030
else:
3131
tn = tempfile.mktemp()
32-
fp = open(tn, "wb")
33-
fp.write(m.group(1) + b"\n")
34-
fp.close()
32+
with open(tn, "wb") as fp:
33+
fp.write(m.group(1) + b"\n")
3534
try:
3635
tn2 = (outfile or tempfile.mktemp())
3736
status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
3837
(tn, tn2))
3938
if status != 0:
4039
raise RuntimeError('OpenSSL x509 failed with status %s and '
4140
'output: %r' % (status, output))
42-
fp = open(tn2, 'rb')
43-
data = fp.read()
44-
fp.close()
41+
with open(tn2, 'rb') as fp:
42+
data = fp.read()
4543
os.unlink(tn2)
4644
return data
4745
finally:
4846
os.unlink(tn)
4947

5048
if sys.platform.startswith("win"):
5149
tfile = tempfile.mktemp()
52-
fp = open(tfile, "w")
53-
fp.write("quit\n")
54-
fp.close()
50+
with open(tfile, "w") as fp:
51+
fp.write("quit\n")
5552
try:
5653
status, output = subproc(
5754
'openssl s_client -connect "%s:%s" -showcerts < "%s"' %

0 commit comments

Comments
 (0)