Skip to content

Commit 90d94be

Browse files
authored
Make more use of python f-strings. NFC (#25804)
Also, remove some other redundant used of `str()` operator when formatting things like exceptions.
1 parent 6913738 commit 90d94be

File tree

4 files changed

+24
-24
lines changed

4 files changed

+24
-24
lines changed

emrun.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -364,10 +364,10 @@ def kill_browser_process():
364364
global browser_process, processname_killed_atexit, current_browser_processes
365365
if browser_process and browser_process.poll() is None:
366366
try:
367-
logv('Terminating browser process pid=' + str(browser_process.pid) + '..')
367+
logv(f'Terminating browser process pid={browser_process.pid}..')
368368
browser_process.kill()
369369
except Exception as e:
370-
logv('Failed with error ' + str(e) + '!')
370+
logv(f'Failed with error {e}!')
371371

372372
browser_process = None
373373
# We have a hold of the target browser process explicitly, no need to resort to killall,
@@ -377,10 +377,10 @@ def kill_browser_process():
377377
if current_browser_processes:
378378
for pid in current_browser_processes:
379379
try:
380-
logv('Terminating browser process pid=' + str(pid['pid']) + '..')
380+
logv(f'Terminating browser process pid={pid["pid"]}..')
381381
os.kill(pid['pid'], 9)
382382
except Exception as e:
383-
logv('Failed with error ' + str(e) + '!')
383+
logv(f'Failed with error {e}!')
384384

385385
current_browser_processes = None
386386
# We have a hold of the target browser process explicitly, no need to resort to killall,
@@ -434,7 +434,7 @@ def pid_existed(pid):
434434
return False
435435

436436
for p in running_browser_processes:
437-
logv('Detected running browser process id: ' + str(p['pid']) + ', existed already at emrun startup? ' + str(pid_existed(p['pid'])))
437+
logv(f'Detected running browser process id: {p["pid"]}, existed already at emrun startup? {pid_existed(p["pid"])}')
438438

439439
current_browser_processes = [p for p in running_browser_processes if not pid_existed(p['pid'])]
440440

@@ -539,15 +539,15 @@ def serve_forever(self, timeout=0.5):
539539
time_since_message = now - last_message_time
540540
if emrun_options.silence_timeout != 0 and time_since_message > emrun_options.silence_timeout:
541541
self.shutdown()
542-
logi('No activity in ' + str(emrun_options.silence_timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--silence-timeout option)')
542+
logi(f'No activity in {emrun_options.silence_timeout} seconds. Quitting web server with return code {emrun_options.timeout_returncode}. (--silence-timeout option)')
543543
page_exit_code = emrun_options.timeout_returncode
544544
emrun_options.kill_exit = True
545545

546546
# If the page has been running too long as a whole, kill process.
547547
time_since_start = now - page_start_time
548548
if emrun_options.timeout != 0 and time_since_start > emrun_options.timeout:
549549
self.shutdown()
550-
logi('Page has not finished in ' + str(emrun_options.timeout) + ' seconds. Quitting web server with return code ' + str(emrun_options.timeout_returncode) + '. (--timeout option)')
550+
logi(f'Page has not finished in {emrun_options.timeout} seconds. Quitting web server with return code {emrun_options.timeout_returncode}. (--timeout option)')
551551
emrun_options.kill_exit = True
552552
page_exit_code = emrun_options.timeout_returncode
553553

@@ -685,7 +685,7 @@ def do_POST(self): # # noqa: DC04
685685
pass
686686
with open(filename, 'wb') as fh:
687687
fh.write(data)
688-
logi('Wrote ' + str(len(data)) + ' bytes to file "' + filename + '".')
688+
logi(f'Wrote {len(data)} bytes to file "{filename}".')
689689
have_received_messages = True
690690
elif path == '/system_info':
691691
system_info = json.loads(get_system_info(format_json=True))
@@ -714,7 +714,7 @@ def do_POST(self): # # noqa: DC04
714714
elif data.startswith('^exit^'):
715715
if not emrun_options.serve_after_exit:
716716
page_exit_code = int(data[6:])
717-
logv('Web page has quit with a call to exit() with return code ' + str(page_exit_code) + '. Shutting down web server. Pass --serve-after-exit to keep serving even after the page terminates with exit().')
717+
logv(f'Web page has quit with a call to exit() with return code ${page_exit_code}. Shutting down web server. Pass --serve-after-exit to keep serving even after the page terminates with exit().')
718718
# Set server socket to nonblocking on shutdown to avoid sporadic deadlocks
719719
self.server.socket.setblocking(False)
720720
self.server.shutdown()
@@ -787,7 +787,7 @@ def get_cpu_info():
787787
except Exception as e:
788788
import traceback
789789
loge(traceback.format_exc())
790-
return {'model': 'Unknown ("' + str(e) + '")',
790+
return {'model': f'Unknown ("{e}")',
791791
'physicalCores': 1,
792792
'logicalCores': 1,
793793
'frequency': 0,
@@ -811,7 +811,7 @@ def get_android_cpu_infoline():
811811
hardware = line[line.find(':') + 1:].strip()
812812

813813
freq = int(check_output([ADB, 'shell', 'cat', '/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq']).strip()) // 1000
814-
return 'CPU: ' + processor + ', ' + hardware + ' @ ' + str(freq) + ' MHz'
814+
return f'CPU: {processor}, {hardware} @ {freq} MHz'
815815

816816

817817
def win_get_gpu_info():
@@ -1435,7 +1435,7 @@ def list_processes_by_name(exe_full_path):
14351435
# Fail gracefully if psutil not available
14361436
logv('import psutil failed, unable to detect browser processes')
14371437

1438-
logv('Searching for processes by full path name "' + exe_full_path + '".. found ' + str(len(pids)) + ' entries')
1438+
logv(f'Searching for processes by full path name "{exe_full_path}".. found {len(pids)} entries')
14391439

14401440
return pids
14411441

@@ -1681,7 +1681,7 @@ def run(args): # noqa: C901, PLR0912, PLR0915
16811681
else:
16821682
hostname = options.hostname
16831683
# create url for browser after opening the server so we have the final port number in case we are binding to port 0
1684-
url = 'http://' + hostname + ':' + str(options.port) + '/' + url
1684+
url = f'http://{hostname}:{options.port}/{url}'
16851685

16861686
if options.android:
16871687
if options.run_browser or options.browser_info:
@@ -1715,7 +1715,7 @@ def run(args): # noqa: C901, PLR0912, PLR0915
17151715
# 5. Locate the name of the main activity for the browser in manifest.txt and add an entry to above list in form 'appname/mainactivityname'
17161716

17171717
if options.android_tunnel:
1718-
subprocess.check_call([ADB, 'reverse', 'tcp:' + str(options.port), 'tcp:' + str(options.port)])
1718+
subprocess.check_call([ADB, 'reverse', f'tcp:{options.port}', f'tcp:{options.port}'])
17191719

17201720
url = url.replace('&', '\\&')
17211721
browser = [ADB, 'shell', 'am', 'start', '-a', 'android.intent.action.VIEW', '-n', browser_app, '-d', url]
@@ -1727,7 +1727,7 @@ def run(args): # noqa: C901, PLR0912, PLR0915
17271727
if options.run_browser or options.browser_info:
17281728
browser = find_browser(str(options.browser))
17291729
if not browser:
1730-
loge('Unable to find browser "' + str(options.browser) + '"! Check the correctness of the passed --browser=xxx parameter!')
1730+
loge(f'Unable to find browser "{options.browser}"! Check the correctness of the passed --browser=xxx parameter!')
17311731
return 1
17321732
browser_exe = browser[0]
17331733
browser_args = shlex.split(unwrap(options.browser_args))
@@ -1783,7 +1783,7 @@ def run(cmd):
17831783
run(['adb', 'shell', 'mkdir', '/mnt/sdcard/safe_firefox_profile'])
17841784
run(['adb', 'push', os.path.join(profile_dir, 'prefs.js'), '/mnt/sdcard/safe_firefox_profile/prefs.js'])
17851785
except Exception as e:
1786-
loge('Creating Firefox profile prefs.js file to internal storage in /mnt/sdcard failed with error ' + str(e) + '!')
1786+
loge(f'Creating Firefox profile prefs.js file to internal storage in /mnt/sdcard failed with error {e}!')
17871787
loge('Try running without --safe-firefox-profile flag if unattended execution mode is not important, or')
17881788
loge('enable rooted debugging on the Android device to allow adb to write files to /mnt/sdcard.')
17891789
browser += ['--es', 'args', '"--profile /mnt/sdcard/safe_firefox_profile"']
@@ -1833,9 +1833,9 @@ def run(cmd):
18331833
logv(browser_exe)
18341834
previous_browser_processes = list_processes_by_name(browser_exe)
18351835
for p in previous_browser_processes:
1836-
logv('Before spawning web browser, found a running ' + os.path.basename(browser_exe) + ' browser process id: ' + str(p['pid']))
1836+
logv(f'Before spawning web browser, found a running {os.path.basename(browser_exe)} browser process id: {p["pid"]}')
18371837
browser_process = subprocess.Popen(browser, env=subprocess_env())
1838-
logv('Launched browser process with pid=' + str(browser_process.pid))
1838+
logv(f'Launched browser process with pid={browser_process.pid}')
18391839
if options.kill_exit:
18401840
atexit.register(kill_browser_process)
18411841
# For Android automation, we execute adb, so this process does not
@@ -1847,7 +1847,7 @@ def run(cmd):
18471847
premature_quit_code = browser_process.poll()
18481848
if premature_quit_code is not None:
18491849
options.serve_after_close = True
1850-
logv('Warning: emrun got immediately detached from the target browser process (the process quit with exit code ' + str(premature_quit_code) + '). Cannot detect when user closes the browser. Behaving as if --serve-after-close was passed in.')
1850+
logv(f'Warning: emrun got immediately detached from the target browser process (the process quit with exit code {premature_quit_code}). Cannot detect when user closes the browser. Behaving as if --serve-after-close was passed in.')
18511851
if not options.browser:
18521852
logv('Try passing the --browser=/path/to/browser option to avoid this from occurring. See https://github.com/emscripten-core/emscripten/issues/3234 for more discussion.')
18531853

tools/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def parse_config_file():
9898
try:
9999
exec(config_text, config)
100100
except Exception as e:
101-
exit_with_error('error in evaluating config file (%s): %s, text: %s', EM_CONFIG, str(e), config_text)
101+
exit_with_error('error in evaluating config file (%s): %s, text: %s', EM_CONFIG, e, config_text)
102102

103103
CONFIG_KEYS = (
104104
'NODE_JS',

tools/extract_metadata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def get_const_expr_value(expr):
6262
elif opcode in (OpCode.GLOBAL_GET,):
6363
return 0
6464
else:
65-
exit_with_error('unexpected opcode in const expr: ' + str(opcode))
65+
exit_with_error('unexpected opcode in const expr: %s', opcode)
6666

6767

6868
def get_global_value(globl):

tools/shared.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ def check_call(cmd, *args, **kw):
186186
except subprocess.CalledProcessError as e:
187187
exit_with_error("'%s' failed (%s)", shlex.join(cmd), returncode_to_str(e.returncode))
188188
except OSError as e:
189-
exit_with_error("'%s' failed: %s", shlex.join(cmd), str(e))
189+
exit_with_error("'%s' failed: %s", shlex.join(cmd), e)
190190

191191

192192
def exec_process(cmd):
@@ -339,7 +339,7 @@ def check_node():
339339
try:
340340
utils.run_process(config.NODE_JS + ['-e', 'console.log("hello")'], stdout=PIPE)
341341
except Exception as e:
342-
exit_with_error('the configured node executable (%s) does not seem to work, check the paths in %s (%s)', config.NODE_JS, config.EM_CONFIG, str(e))
342+
exit_with_error('the configured node executable (%s) does not seem to work, check the paths in %s (%s)', config.NODE_JS, config.EM_CONFIG, e)
343343

344344

345345
def generate_sanity():
@@ -517,7 +517,7 @@ def setup_temp_dirs():
517517
try:
518518
safe_ensure_dirs(EMSCRIPTEN_TEMP_DIR)
519519
except Exception as e:
520-
exit_with_error(str(e) + f'Could not create canonical temp dir. Check definition of TEMP_DIR in {config.EM_CONFIG}')
520+
exit_with_error('error creating canonical temp dir (Check definition of TEMP_DIR in %s): %s', config.EM_CONFIG, e)
521521

522522
# Since the canonical temp directory is, by definition, the same
523523
# between all processes that run in DEBUG mode we need to use a multi

0 commit comments

Comments
 (0)