Skip to content

Commit 8977c4f

Browse files
authored
Explicitly close file descriptors in python code. NFC (#14074)
1 parent 4013414 commit 8977c4f

35 files changed

+168
-124
lines changed

emcc.py

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
from tools import colored_logger, diagnostics, building
4343
from tools.shared import unsuffixed, unsuffixed_basename, WINDOWS, safe_copy
4444
from tools.shared import run_process, read_and_preprocess, exit_with_error, DEBUG
45+
from tools.shared import read_file, write_file, read_binary
4546
from tools.shared import do_replace, strip_prefix
4647
from tools.response_file import substitute_response_files
4748
from tools.minimal_runtime_shell import generate_minimal_runtime_html
@@ -357,7 +358,7 @@ def standardize_setting_change(key, value):
357358
filename = strip_prefix(value, '@')
358359
if not os.path.exists(filename):
359360
exit_with_error('%s: file not found parsing argument: %s=%s' % (filename, key, value))
360-
value = open(filename).read().strip()
361+
value = read_file(filename).strip()
361362
else:
362363
value = value.replace('\\', '\\\\')
363364

@@ -589,7 +590,7 @@ def check_human_readable_list(items):
589590

590591

591592
def make_js_executable(script):
592-
src = open(script).read()
593+
src = read_file(script)
593594
cmd = shared.shlex_join(config.JS_ENGINE)
594595
if not os.path.isabs(config.JS_ENGINE[0]):
595596
# TODO: use whereis etc. And how about non-*NIX?
@@ -1350,19 +1351,19 @@ def phase_linker_setup(options, state, newargs, settings_map):
13501351
add_link_flag(state, sys.maxsize, f)
13511352

13521353
if options.emrun:
1353-
options.pre_js += open(shared.path_from_root('src', 'emrun_prejs.js')).read() + '\n'
1354-
options.post_js += open(shared.path_from_root('src', 'emrun_postjs.js')).read() + '\n'
1354+
options.pre_js += read_file(shared.path_from_root('src', 'emrun_prejs.js')) + '\n'
1355+
options.post_js += read_file(shared.path_from_root('src', 'emrun_postjs.js')) + '\n'
13551356
# emrun mode waits on program exit
13561357
settings.EXIT_RUNTIME = 1
13571358

13581359
if options.cpu_profiler:
1359-
options.post_js += open(shared.path_from_root('src', 'cpuprofiler.js')).read() + '\n'
1360+
options.post_js += read_file(shared.path_from_root('src', 'cpuprofiler.js')) + '\n'
13601361

13611362
if options.memory_profiler:
13621363
settings.MEMORYPROFILER = 1
13631364

13641365
if options.thread_profiler:
1365-
options.post_js += open(shared.path_from_root('src', 'threadprofiler.js')).read() + '\n'
1366+
options.post_js += read_file(shared.path_from_root('src', 'threadprofiler.js')) + '\n'
13661367

13671368
if options.memory_init_file is None:
13681369
options.memory_init_file = settings.OPT_LEVEL >= 2
@@ -2527,7 +2528,7 @@ def phase_source_transforms(options, target):
25272528
# Apply pre and postjs files
25282529
if final_js and (options.pre_js or options.post_js):
25292530
logger.debug('applying pre/postjses')
2530-
src = open(final_js).read()
2531+
src = read_file(final_js)
25312532
final_js += '.pp.js'
25322533
with open(final_js, 'w') as f:
25332534
# pre-js code goes right after the Module integration code (so it
@@ -2553,9 +2554,9 @@ def phase_memory_initializer(memfile):
25532554
# is set the memory initializer url.
25542555
global final_js
25552556

2556-
src = open(final_js).read()
2557+
src = read_file(final_js)
25572558
src = do_replace(src, '// {{MEM_INITIALIZER}}', 'var memoryInitializer = "%s";' % os.path.basename(memfile))
2558-
open(final_js + '.mem.js', 'w').write(src)
2559+
write_file(final_js + '.mem.js', src)
25592560
final_js += '.mem.js'
25602561

25612562

@@ -2565,9 +2566,9 @@ def phase_final_emitting(options, state, target, wasm_target, memfile):
25652566

25662567
# Remove some trivial whitespace
25672568
# TODO: do not run when compress has already been done on all parts of the code
2568-
# src = open(final_js).read()
2569+
# src = read_file(final_js)
25692570
# src = re.sub(r'\n+[ \n]*\n+', '\n', src)
2570-
# open(final_js, 'w').write(src)
2571+
# write_file(final_js, src)
25712572

25722573
if settings.USE_PTHREADS:
25732574
target_dir = os.path.dirname(os.path.abspath(target))
@@ -2578,7 +2579,7 @@ def phase_final_emitting(options, state, target, wasm_target, memfile):
25782579
# Minify the worker.js file in optimized builds
25792580
if (settings.OPT_LEVEL >= 1 or settings.SHRINK_LEVEL >= 1) and not settings.DEBUG_LEVEL:
25802581
minified_worker = building.acorn_optimizer(worker_output, ['minifyWhitespace'], return_output=True)
2581-
open(worker_output, 'w').write(minified_worker)
2582+
write_file(worker_output, minified_worker)
25822583

25832584
# track files that will need native eols
25842585
generated_text_files_with_native_eols = []
@@ -2599,16 +2600,15 @@ def phase_final_emitting(options, state, target, wasm_target, memfile):
25992600
# Unmangle previously mangled `import.meta` references in both main code and libraries.
26002601
# See also: `preprocess` in parseTools.js.
26012602
if settings.EXPORT_ES6 and settings.USE_ES6_IMPORT_META:
2602-
src = open(final_js).read()
2603+
src = read_file(final_js)
26032604
final_js += '.esmeta.js'
2604-
with open(final_js, 'w') as f:
2605-
f.write(src.replace('EMSCRIPTEN$IMPORT$META', 'import.meta'))
2605+
write_file(final_js, src.replace('EMSCRIPTEN$IMPORT$META', 'import.meta'))
26062606
save_intermediate('es6-import-meta')
26072607

26082608
# Apply pre and postjs files
26092609
if options.extern_pre_js or options.extern_post_js:
26102610
logger.debug('applying extern pre/postjses')
2611-
src = open(final_js).read()
2611+
src = read_file(final_js)
26122612
final_js += '.epp.js'
26132613
with open(final_js, 'w') as f:
26142614
f.write(fix_windows_newlines(options.extern_pre_js))
@@ -2753,13 +2753,13 @@ def consume_arg_file():
27532753
elif check_arg('--js-transform'):
27542754
options.js_transform = consume_arg()
27552755
elif check_arg('--pre-js'):
2756-
options.pre_js += open(consume_arg_file()).read() + '\n'
2756+
options.pre_js += read_file(consume_arg_file()) + '\n'
27572757
elif check_arg('--post-js'):
2758-
options.post_js += open(consume_arg_file()).read() + '\n'
2758+
options.post_js += read_file(consume_arg_file()) + '\n'
27592759
elif check_arg('--extern-pre-js'):
2760-
options.extern_pre_js += open(consume_arg_file()).read() + '\n'
2760+
options.extern_pre_js += read_file(consume_arg_file()) + '\n'
27612761
elif check_arg('--extern-post-js'):
2762-
options.extern_post_js += open(consume_arg_file()).read() + '\n'
2762+
options.extern_post_js += read_file(consume_arg_file()) + '\n'
27632763
elif check_arg('--compiler-wrapper'):
27642764
config.COMPILER_WRAPPER = consume_arg()
27652765
elif check_flag('--post-link'):
@@ -3177,10 +3177,10 @@ def run_closure_compiler():
31773177

31783178
# replace placeholder strings with correct subresource locations
31793179
if final_js and settings.SINGLE_FILE and not settings.WASM2JS:
3180-
js = open(final_js).read()
3180+
js = read_file(final_js)
31813181

31823182
if settings.MINIMAL_RUNTIME:
3183-
js = do_replace(js, '<<< WASM_BINARY_DATA >>>', base64_encode(open(wasm_target, 'rb').read()))
3183+
js = do_replace(js, '<<< WASM_BINARY_DATA >>>', base64_encode(read_binary(wasm_target)))
31843184
else:
31853185
js = do_replace(js, '<<< WASM_BINARY_FILE >>>', shared.JS.get_subresource_location(wasm_target))
31863186
shared.try_delete(wasm_target)
@@ -3191,7 +3191,7 @@ def run_closure_compiler():
31913191
def modularize():
31923192
global final_js
31933193
logger.debug('Modularizing, assigning to var ' + settings.EXPORT_NAME)
3194-
src = open(final_js).read()
3194+
src = read_file(final_js)
31953195

31963196
return_value = settings.EXPORT_NAME
31973197
if settings.WASM_ASYNC_COMPILATION:
@@ -3386,7 +3386,7 @@ def generate_traditional_runtime_html(target, options, js_target, target_basenam
33863386
if settings.SINGLE_FILE:
33873387
js_contents = script.inline or ''
33883388
if script.src:
3389-
js_contents += open(js_target).read()
3389+
js_contents += read_file(js_target)
33903390
shared.try_delete(js_target)
33913391
script.src = None
33923392
script.inline = js_contents
@@ -3479,13 +3479,13 @@ def generate_worker_js(target, js_target, target_basename):
34793479
proxy_worker_filename = (settings.PROXY_TO_WORKER_FILENAME or worker_target_basename) + '.js'
34803480

34813481
target_contents = worker_js_script(proxy_worker_filename)
3482-
open(target, 'w').write(target_contents)
3482+
write_file(target, target_contents)
34833483

34843484

34853485
def worker_js_script(proxy_worker_filename):
3486-
web_gl_client_src = open(shared.path_from_root('src', 'webGLClient.js')).read()
3487-
idb_store_src = open(shared.path_from_root('src', 'IDBStore.js')).read()
3488-
proxy_client_src = open(shared.path_from_root('src', 'proxyClient.js')).read()
3486+
web_gl_client_src = read_file(shared.path_from_root('src', 'webGLClient.js'))
3487+
idb_store_src = read_file(shared.path_from_root('src', 'IDBStore.js'))
3488+
proxy_client_src = read_file(shared.path_from_root('src', 'proxyClient.js'))
34893489
proxy_client_src = do_replace(proxy_client_src, '{{{ filename }}}', proxy_worker_filename)
34903490
proxy_client_src = do_replace(proxy_client_src, '{{{ IDBStore.js }}}', idb_store_src)
34913491
return web_gl_client_src + '\n' + proxy_client_src

emrun.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,8 @@ def do_POST(self):
691691
except OSError:
692692
pass
693693
filename = os.path.join(dump_out_directory, os.path.normpath(filename))
694-
open(filename, 'wb').write(data)
694+
with open(filename, 'wb') as fh:
695+
fh.write(data)
695696
logi('Wrote ' + str(len(data)) + ' bytes to file "' + filename + '".')
696697
have_received_messages = True
697698
elif path == '/system_info':
@@ -1060,7 +1061,8 @@ def get_computer_model():
10601061
model = check_output(cmd)
10611062
model = re.search('<configCode>(.*)</configCode>', model)
10621063
model = model.group(1).strip()
1063-
open(os.path.join(os.getenv("HOME"), '.emrun.hwmodel.cached'), 'w').write(model) # Cache the hardware model to disk
1064+
with open(os.path.join(os.getenv("HOME"), '.emrun.hwmodel.cached'), 'w') as fh:
1065+
fh.write(model) # Cache the hardware model to disk
10641066
return model
10651067
except Exception:
10661068
hwmodel = check_output(['sysctl', 'hw.model'])
@@ -1385,7 +1387,8 @@ def get_system_info(format_json):
13851387
return info.strip()
13861388
else:
13871389
try:
1388-
unique_system_id = open(os.path.expanduser('~/.emrun.generated.guid'), 'r').read().strip()
1390+
with open(os.path.expanduser('~/.emrun.generated.guid')) as fh:
1391+
unique_system_id = fh.read().strip()
13891392
except Exception:
13901393
import uuid
13911394
unique_system_id = str(uuid.uuid4())

site/source/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import sys
2020
import os
21+
from pathlib import Path
2122

2223

2324
# At the top. #HamishW https://pypi.python.org/pypi/sphinx-bootstrap-theme/ ...
@@ -93,8 +94,7 @@
9394
# |version| and |release|, also used in various other places throughout the
9495
# built documents.
9596
#
96-
97-
emscripten_version = open(os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'emscripten-version.txt'))).read().strip().replace('"', '')
97+
emscripten_version = Path(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'emscripten-version.txt').resolve().read_text().strip().replace('"', '')
9898

9999
# The short X.Y version.
100100
version = emscripten_version[:emscripten_version.rindex('.')]

site/source/get_wiki.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import stat
2323
import sys
2424
import time
25+
from pathlib import Path
2526

2627
import api_items
2728

@@ -91,7 +92,7 @@ def ConvertFilesToRst():
9192
continue
9293

9394
inputfilename = wiki_checkout + file
94-
markdown = open(inputfilename).read()
95+
markdown = Path(inputfilename).read_text()
9596
if 'This article has moved from the wiki to the new site' in markdown:
9697
continue
9798
if 'This page has been migrated to the main site' in markdown:

tools/clean_webconsole.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import os
1010
import re
1111
import sys
12+
from pathlib import Path
1213

1314
__rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1415

@@ -21,8 +22,11 @@ def nice(x):
2122
return '0x' + ('0' * (len(x) - 6)) + x[2:].upper()
2223

2324

24-
repdata = open(path_from_root('system', 'include', 'GL', 'gl.h')).readlines() + ['\n'] + \
25-
open(path_from_root('system', 'include', 'GL', 'glext.h')).readlines()
25+
repdata = (
26+
Path(path_from_root('system', 'include', 'GL', 'gl.h')).read_text().splitline(keepends=True) +
27+
['\n'] +
28+
Path(path_from_root('system', 'include', 'GL', 'glext.h')).read_text().splitlines(keepends=True)
29+
)
2630
reps = {}
2731
for rep in repdata:
2832
rep = rep.replace('\t', ' ').replace('\n', '')

tools/config.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,8 @@ def parse_config_file():
106106
Also check EM_<KEY> environment variables to override specific config keys.
107107
"""
108108
config = {}
109-
config_text = open(EM_CONFIG, 'r').read()
109+
with open(EM_CONFIG) as fh:
110+
config_text = fh.read()
110111
try:
111112
exec(config_text, config)
112113
except Exception as e:
@@ -171,7 +172,9 @@ def parse_config_file():
171172
def generate_config(path, first_time=False):
172173
# Note: repr is used to ensure the paths are escaped correctly on Windows.
173174
# The full string is replaced so that the template stays valid Python.
174-
config_data = open(path_from_root('tools', 'settings_template.py')).read().splitlines()
175+
176+
with open(path_from_root('tools', 'settings_template.py')) as fh:
177+
config_data = fh.read().splitlines()
175178
config_data = config_data[3:] # remove the initial comment
176179
config_data = '\n'.join(config_data)
177180
# autodetect some default paths

tools/ctor_evaller.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def eval_ctors(js, wasm_file, num):
9393

9494
# main
9595
def main():
96-
js = open(js_file).read()
96+
js = shared.read_file(js_file)
9797
ctors_start, ctors_end = find_ctors(js)
9898
if ctors_start < 0:
9999
logger.debug('ctor_evaller: no ctors')
@@ -114,7 +114,7 @@ def main():
114114
logger.debug('ctor_evaller: not successful')
115115
sys.exit(0)
116116
logger.debug('ctor_evaller: we managed to remove %d ctors' % num_successful)
117-
open(js_file, 'w').write(new_js)
117+
shared.write_file(js_file, new_js)
118118

119119

120120
if __name__ == '__main__':

tools/debug/autodediffer.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
from __future__ import print_function
1313
import os, sys
1414

15+
from pathlib import Path
16+
1517

1618
def process_line(line):
1719
#AD:2041,0.900000
@@ -20,8 +22,8 @@ def process_line(line):
2022
num, val = line.split(',')
2123
return [int(num), float(val)]
2224

23-
a = open(sys.argv[1], 'r').readlines()
24-
b = open(sys.argv[2], 'r').readlines()
25+
a = Path(sys.argv[1]).read_text().splitlines(keepends=True)
26+
b = Path(sys.argv[2]).read_text().splitlines(keepends=True)
2527
MIN = 0.0001 if len(sys.argv) < 4 else sys.argv[3]
2628

2729
ai = 0

tools/debug/bisect_pair.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,20 @@
1111

1212
from __future__ import print_function
1313
import os, sys, shutil
14+
from pathlib import Path
1415
from subprocess import Popen, PIPE, STDOUT
1516

1617
__rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
18+
19+
1720
def path_from_root(*pathelems):
1821
return os.path.join(__rootpath__, *pathelems)
19-
exec(open(path_from_root('tools', 'shared.py'), 'r').read())
20-
21-
file1 = open(sys.argv[1]).read()
22-
file2 = open(sys.argv[2]).read()
22+
23+
exec(Path(path_from_root('tools', 'shared.py').read_text()))
2324

24-
leftf = open('left', 'w')
25-
leftf.write(file1)
26-
leftf.close()
25+
shutil.copyfile(sys.argv[1], 'left')
26+
shutil.copyfile(sys.argv[2], 'right')
2727

28-
rightf = open('right', 'w')
29-
rightf.write(file2)
30-
rightf.close()
3128

3229
def run_code(name):
3330
ret = run_js(name, stderr=PIPE, full_output=True, assert_returncode=None, engine=SPIDERMONKEY_ENGINE)

tools/debug/bisect_pair_lines.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,18 @@
1313

1414
from __future__ import print_function
1515
import os, sys, shutil
16+
from pathlib import Path
1617
from subprocess import Popen, PIPE, STDOUT
1718

1819
__rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1920
def path_from_root(*pathelems):
2021
return os.path.join(__rootpath__, *pathelems)
21-
exec(open(path_from_root('tools', 'shared.py'), 'r').read())
22+
23+
exec(Path(path_from_root('tools', 'shared.py').read())
2224

23-
file1 = open(sys.argv[1]).read()
24-
file2 = open(sys.argv[2]).read()
25+
shutil.copyfile(sys.argv[1], 'left')
26+
shutil.copyfile(sys.argv[2], 'right')
2527

26-
leftf = open('left', 'w')
27-
leftf.write(file1)
28-
leftf.close()
29-
30-
rightf = open('right', 'w')
31-
rightf.write(file2)
32-
rightf.close()
3328

3429
def run_code(name):
3530
ret = run_js(name, stderr=PIPE, full_output=True)
@@ -53,7 +48,7 @@ def run_code(name):
5348
while True:
5449
mid = int((low + high)/2)
5550
print(low, high, ' current: %d' % mid, end=' ')
56-
open('middle', 'w').write('\n'.join(left_lines[:mid] + right_lines[mid:]))
51+
Path('middle').write_text('\n'.join(left_lines[:mid] + right_lines[mid:]))
5752
shutil.copyfile('middle', 'middle' + str(mid))
5853
result = run_code('middle')
5954
print(result == left_result, result == right_result)#, 'XXX', left_result, 'YYY', result, 'ZZZ', right_result

0 commit comments

Comments
 (0)