Skip to content

Commit 172bb39

Browse files
bpo-22831: Use "with" to avoid possible fd leaks in tools (part 2). (pythonGH-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()

0 commit comments

Comments
 (0)