Skip to content

Commit 1f2a39c

Browse files
committedDec 22, 2015
Tidy up Python file handlers
Rather than using `f = open(path).read()`, which leaves the file open for an indeterminate period of time, switch to the `with open(path) as f` idiom, which ensures the file is always closed correctly.
1 parent 37b827c commit 1f2a39c

File tree

8 files changed

+48
-50
lines changed

8 files changed

+48
-50
lines changed
 

Diff for: ‎utils/apply-fixit-edits.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ def apply_edits(path):
3434

3535
edits_set = set()
3636
for remap_file in remap_files:
37-
json_data = open(remap_file).read()
37+
with open(remap_file) as f:
38+
json_data = f.read()
3839
json_data = json_data.replace(",\n }", "\n }")
3940
json_data = json_data.replace(",\n]", "\n]")
4041
curr_edits = json.loads(json_data)
@@ -55,13 +56,15 @@ def apply_edits(path):
5556
for fname, edits in edits_per_file.iteritems():
5657
print('Updating', fname)
5758
edits.sort(reverse=True)
58-
file_data = open(fname).read()
59+
with open(fname) as f:
60+
file_data = f.read()
5961
for ed in edits:
6062
offset = ed[0]
6163
length = ed[1]
6264
text = ed[2]
6365
file_data = file_data[:offset] + str(text) + file_data[offset+length:]
64-
open(fname, 'w').write(file_data)
66+
with open(fname, 'w') as f:
67+
f.write(file_data)
6568
return 0
6669

6770
def main():

Diff for: ‎utils/gyb.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -364,9 +364,13 @@ class ParseContext:
364364
tokens = None # The rest of the tokens
365365
closeLines = False
366366

367-
def __init__(self, filename, template = None):
367+
def __init__(self, filename, template=None):
368368
self.filename = os.path.abspath(filename)
369-
self.template = template or open(filename).read()
369+
if template is None:
370+
with open(filename) as f:
371+
self.template = f.read()
372+
else:
373+
self.template = template
370374
self.lineStarts = getLineStarts(self.template)
371375
self.tokens = self.tokenGenerator(tokenizeTemplate(self.template))
372376
self.nextToken()

Diff for: ‎utils/pre-commit-benchmark

+5-3
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,8 @@ def collectBenchmarks(exeNames, treeish = None, repeat = 3, build_script_args =
133133

134134
rebuilt = True
135135
else:
136-
timingsText = open(timingsFile).read()
136+
with open(timingsFile) as f:
137+
timingsText = f.read()
137138
oldRepeat = timingsText.count('\nTotal')
138139
if oldRepeat < repeat:
139140
print('Only %s repeats in existing %s timings file' % (oldRepeat, exe))
@@ -146,8 +147,9 @@ def collectBenchmarks(exeNames, treeish = None, repeat = 3, build_script_args =
146147
output = check_output(os.path.join(binDir, exe))
147148
print(output)
148149
timingsText += output
149-
150-
open(timingsFile, 'w').write(timingsText)
150+
151+
with open(timingsFile, 'w') as outfile:
152+
outfile.write(timingsText)
151153
print('done.')
152154

153155
return cacheDir

Diff for: ‎utils/protocol_graph.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ def bodyLines(bodyText):
7676
comments = r'//.* | /[*] (.|\n)*? [*]/' # FIXME: doesn't respect strings or comment nesting)
7777

7878
# read source, stripping all comments
79-
sourceSansComments = re.sub(comments, '', open(args[1]).read(), flags=reFlags)
79+
with open(args[1]) as src:
80+
sourceSansComments = re.sub(comments, '', src.read(), flags=reFlags)
8081

8182
genericParameterConstraint = interpolate(r' (%(identifier)s) \s* : \s* (%(identifier)s) ')
8283

Diff for: ‎utils/sil-opt-verify-all-modules.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,8 @@ def run_commands_in_parallel(commands):
113113
makefile += "all: " + " ".join(targets) + "\n"
114114

115115
temp_dir = tempfile.mkdtemp(prefix="swift-testsuite-main")
116-
makefile_file = open(os.path.join(temp_dir, 'Makefile'), 'w')
117-
makefile_file.write(makefile)
118-
makefile_file.close()
116+
with open(os.path.join(temp_dir, 'Makefile'), 'w') as makefile_file:
117+
makefile_file.write(makefile)
119118

120119
max_processes = multiprocessing.cpu_count()
121120
subprocess.check_call([

Diff for: ‎utils/swift-bench.py

+6-9
Original file line numberDiff line numberDiff line change
@@ -154,9 +154,8 @@ def processSource(self, name):
154154
"""
155155

156156
benchRE = re.compile("^\s*func\s\s*bench_([a-zA-Z0-9_]+)\s*\(\s*\)\s*->\s*Int\s*({)?\s*$")
157-
f = open(name)
158-
lines = f.readlines()
159-
f.close()
157+
with open(name) as f:
158+
lines = list(f)
160159
output = header
161160
lookingForCurlyBrace = False
162161
testNames = []
@@ -190,9 +189,8 @@ def processSource(self, name):
190189
output += mainBody % (n, n)
191190
processedName = 'processed_' + os.path.basename(name)
192191
output += mainEnd
193-
f = open(processedName, 'w')
194-
f.write(output)
195-
f.close()
192+
with open(processedName, 'w') as f:
193+
f.write(output)
196194
for n in testNames:
197195
self.tests[name+":"+n].processedSource = processedName
198196

@@ -210,9 +208,8 @@ def compileOpaqueCFile(self):
210208
extern "C" int32_t opaqueGetInt32(int32_t x) { return x; }
211209
extern "C" int64_t opaqueGetInt64(int64_t x) { return x; }
212210
"""
213-
f = open('opaque.cpp', 'w')
214-
f.write(fileBody)
215-
f.close()
211+
with open('opaque.cpp', 'w') as f:
212+
f.write(fileBody)
216213
# TODO: Handle subprocess.CalledProcessError for this call:
217214
self.runCommand(['clang++', 'opaque.cpp', '-o', 'opaque.o', '-c', '-O2'])
218215

Diff for: ‎utils/viewcfg

+19-21
Original file line numberDiff line numberDiff line change
@@ -138,27 +138,25 @@ def main():
138138
# Write the output dot file.
139139

140140
fileName = tempfile.gettempdir() + "/viewcfg" + suffix + ".dot"
141-
outFile = open(fileName, "w")
142-
143-
outFile.write('digraph "CFG" {\n')
144-
for name, block in blocks.iteritems():
145-
if block.content is not None:
146-
outFile.write("\tNode" + str(block.index) +
147-
" [shape=record,label=\"{" + block.content + "}\"];\n")
148-
else:
149-
outFile.write("\tNode" + str(block.index) +
150-
" [shape=record,color=gray,fontcolor=gray,label=\"{" +
151-
block.name + "}\"];\n")
152-
153-
for succName in block.getSuccs():
154-
succBlock = blocks[succName]
155-
outFile.write("\tNode" + str(block.index) + " -> Node" +
156-
str(succBlock.index) + ";\n")
157-
158-
outFile.write("}\n")
159-
outFile.flush()
160-
os.fsync(outFile.fileno())
161-
outFile.close
141+
with open(fileName 'w') as outFile:
142+
outFile = open(fileName, "w")
143+
144+
outFile.write('digraph "CFG" {\n')
145+
for name, block in blocks.iteritems():
146+
if block.content is not None:
147+
outFile.write("\tNode" + str(block.index) +
148+
" [shape=record,label=\"{" + block.content + "}\"];\n")
149+
else:
150+
outFile.write("\tNode" + str(block.index) +
151+
" [shape=record,color=gray,fontcolor=gray,label=\"{" +
152+
block.name + "}\"];\n")
153+
154+
for succName in block.getSuccs():
155+
succBlock = blocks[succName]
156+
outFile.write("\tNode" + str(block.index) + " -> Node" +
157+
str(succBlock.index) + ";\n")
158+
159+
outFile.write("}\n")
162160

163161
# Open the dot file (should be done with Graphviz).
164162

Diff for: ‎validation-test/stdlib/Slice/Inputs/GenerateSliceTests.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
]:
2020
Base = '%s%s%sCollection' % (base_kind, traversal, 'Mutable' if mutable else '')
2121
testFilename = WrapperType + '_Of_' + Base + '_' + name + '.swift'
22-
testFile = open(testFilename + '.gyb', 'w')
23-
testFile.write("""
22+
with open(testFilename + '.gyb', 'w') as testFile:
23+
testFile.write("""
2424
//// Automatically Generated From validation-test/stdlib/Inputs/GenerateSliceTests.py
2525
//////// Do Not Edit Directly!
2626
// -*- swift -*-
@@ -69,9 +69,3 @@
6969
prefix=prefix,
7070
suffix=suffix
7171
))
72-
testFile.close()
73-
74-
75-
76-
77-

0 commit comments

Comments
 (0)