From 55390d273f36f49da3896e687ac5530f40c1d150 Mon Sep 17 00:00:00 2001 From: Ewout ter Hoeven Date: Thu, 16 Dec 2021 14:58:17 +0100 Subject: [PATCH] Convert format strings strings to f-strings (#23241) * Convert all text strings to f-strings Reformats all the text from the old "%-formatted" and .format(...) format to the newer f-string format, as defined in PEP 498. This requires Python 3.6+. Flynt 0.69 was used to reformat the strings. 120 f-strings were created in 51 files. F-strings are in general more readable, concise and performant. See also: https://www.python.org/dev/peps/pep-0498/#rationale * revert pyextra changes * revert ublox.py Co-authored-by: Willem Melching --- common/ffi_wrapper.py | 2 +- common/file_helpers.py | 2 +- common/profiler.py | 2 +- common/realtime.py | 2 +- common/tests/test_file_helpers.py | 2 +- common/timeout.py | 2 +- selfdrive/camerad/test/test_camerad.py | 2 +- selfdrive/car/car_helpers.py | 4 +-- selfdrive/car/fingerprints.py | 2 +- selfdrive/car/fw_versions.py | 4 +-- selfdrive/car/honda/interface.py | 2 +- selfdrive/car/tests/test_car_interfaces.py | 2 +- selfdrive/car/volkswagen/interface.py | 2 +- .../lib/longitudinal_mpc_lib/long_mpc.py | 3 +-- selfdrive/controls/lib/radar_helpers.py | 2 +- selfdrive/controls/radard.py | 2 +- selfdrive/controls/tests/test_alerts.py | 2 +- selfdrive/debug/can_printer.py | 2 +- selfdrive/debug/check_freq.py | 2 +- selfdrive/debug/cpu_usage_stat.py | 4 +-- selfdrive/debug/dump.py | 4 +-- selfdrive/debug/get_fingerprint.py | 4 +-- selfdrive/debug/internal/power_monitor.py | 6 ++--- selfdrive/debug/live_cpu_and_temp.py | 2 +- selfdrive/hardware/tici/power_monitor.py | 6 ++--- selfdrive/loggerd/deleter.py | 4 +-- selfdrive/loggerd/tools/mark_unuploaded.py | 2 +- selfdrive/loggerd/uploader.py | 2 +- selfdrive/manager/process.py | 10 +++---- selfdrive/modeld/visiontest.py | 2 +- selfdrive/test/openpilotci.py | 2 +- selfdrive/test/process_replay/model_replay.py | 2 +- .../test/process_replay/test_processes.py | 26 +++++++++---------- selfdrive/test/process_replay/update_refs.py | 2 +- selfdrive/test/test_fingerprints.py | 6 ++--- selfdrive/test/test_models.py | 2 +- selfdrive/test/update_ci_routes.py | 6 ++--- selfdrive/updated.py | 2 +- selfdrive/version.py | 12 ++++----- tools/lib/framereader.py | 10 +++---- tools/lib/route.py | 4 +-- tools/lib/url_file.py | 2 +- tools/replay/lib/ui_helpers.py | 2 +- tools/scripts/fetch_image_from_route.py | 4 +-- tools/scripts/save_ubloxraw_stream.py | 2 +- tools/scripts/setup_ssh_keys.py | 2 +- tools/sim/lib/manual_ctrl.py | 16 ++++++------ 47 files changed, 95 insertions(+), 96 deletions(-) diff --git a/common/ffi_wrapper.py b/common/ffi_wrapper.py index e6ee2c23f7af86..a228b40256abf1 100644 --- a/common/ffi_wrapper.py +++ b/common/ffi_wrapper.py @@ -28,7 +28,7 @@ def ffi_wrap(name, c_code, c_header, tmpdir="/tmp/ccache", cflags="", libraries= try: mod = __import__(cache) except Exception: - print("cache miss {0}".format(cache)) + print(f"cache miss {cache}") compile_code(cache, c_code, c_header, tmpdir, cflags, libraries) mod = __import__(cache) finally: diff --git a/common/file_helpers.py b/common/file_helpers.py index 2037a665b060dc..3373d82a03daaa 100644 --- a/common/file_helpers.py +++ b/common/file_helpers.py @@ -35,7 +35,7 @@ def get_tmpdir_on_same_filesystem(path): if len(parts) > 1 and parts[1] == "scratch": return "/scratch/tmp" elif len(parts) > 2 and parts[2] == "runner": - return "/{}/runner/tmp".format(parts[1]) + return f"/{parts[1]}/runner/tmp" return "/tmp" diff --git a/common/profiler.py b/common/profiler.py index e4d208acaeb058..8b1a7a8cfa53dd 100644 --- a/common/profiler.py +++ b/common/profiler.py @@ -42,4 +42,4 @@ def display(self): print("%30s: %9.2f avg: %7.2f percent: %3.0f IGNORED" % (n, ms*1000.0, ms*1000.0/self.iter, ms/self.tot*100)) else: print("%30s: %9.2f avg: %7.2f percent: %3.0f" % (n, ms*1000.0, ms*1000.0/self.iter, ms/self.tot*100)) - print("Iter clock: %2.6f TOTAL: %2.2f" % (self.tot/self.iter, self.tot)) + print(f"Iter clock: {self.tot / self.iter:2.6f} TOTAL: {self.tot:2.2f}") diff --git a/common/realtime.py b/common/realtime.py index 762410f09e41e8..697e816369814a 100644 --- a/common/realtime.py +++ b/common/realtime.py @@ -79,7 +79,7 @@ def monitor_time(self) -> bool: remaining = self._next_frame_time - sec_since_boot() self._next_frame_time += self._interval if self._print_delay_threshold is not None and remaining < -self._print_delay_threshold: - print("%s lagging by %.2f ms" % (self._process_name, -remaining * 1000)) + print(f"{self._process_name} lagging by {-remaining * 1000:.2f} ms") lagged = True self._frame += 1 self._remaining = remaining diff --git a/common/tests/test_file_helpers.py b/common/tests/test_file_helpers.py index 344455ba6ce7e4..d39e66de135473 100644 --- a/common/tests/test_file_helpers.py +++ b/common/tests/test_file_helpers.py @@ -8,7 +8,7 @@ class TestFileHelpers(unittest.TestCase): def run_atomic_write_func(self, atomic_write_func): - path = "/tmp/tmp{}".format(uuid4()) + path = f"/tmp/tmp{uuid4()}" with atomic_write_func(path) as f: f.write("test") diff --git a/common/timeout.py b/common/timeout.py index 4d424cdc0a865c..d0b0ce0630af78 100644 --- a/common/timeout.py +++ b/common/timeout.py @@ -12,7 +12,7 @@ class Timeout: """ def __init__(self, seconds, error_msg=None): if error_msg is None: - error_msg = 'Timed out after {} seconds'.format(seconds) + error_msg = f'Timed out after {seconds} seconds' self.seconds = seconds self.error_msg = error_msg diff --git a/selfdrive/camerad/test/test_camerad.py b/selfdrive/camerad/test/test_camerad.py index 11e070f328b594..ff37ad1f311936 100755 --- a/selfdrive/camerad/test/test_camerad.py +++ b/selfdrive/camerad/test/test_camerad.py @@ -54,7 +54,7 @@ def test_frame_packets(self): self.assertTrue(abs(dfid - 1) <= SKIP_FRAME_TOLERANCE, "%s frame id diff is %d" % (camera, dfid)) dts = ct - last_ts[camera] - self.assertTrue(abs(dts - (1000/CAMERAS[camera])) < LAG_FRAME_TOLERANCE, "%s frame t(ms) diff is %f" % (camera, dts)) + self.assertTrue(abs(dts - (1000/CAMERAS[camera])) < LAG_FRAME_TOLERANCE, f"{camera} frame t(ms) diff is {dts:f}") last_frame_id[camera] = sm[camera].frameId last_ts[camera] = ct diff --git a/selfdrive/car/car_helpers.py b/selfdrive/car/car_helpers.py index 2481c6e94b1afb..5c4208625e7d64 100644 --- a/selfdrive/car/car_helpers.py +++ b/selfdrive/car/car_helpers.py @@ -39,7 +39,7 @@ def get_one_can(logcan): def load_interfaces(brand_names): ret = {} for brand_name in brand_names: - path = ('selfdrive.car.%s' % brand_name) + path = f'selfdrive.car.{brand_name}' CarInterface = __import__(path + '.interface', fromlist=['CarInterface']).CarInterface if os.path.exists(BASEDIR + '/' + path.replace('.', '/') + '/carstate.py'): @@ -65,7 +65,7 @@ def _get_interface_names(): for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]: try: brand_name = car_folder.split('/')[-1] - model_names = __import__('selfdrive.car.%s.values' % brand_name, fromlist=['CAR']).CAR + model_names = __import__(f'selfdrive.car.{brand_name}.values', fromlist=['CAR']).CAR model_names = [getattr(model_names, c) for c in model_names.__dict__.keys() if not c.startswith("__")] brand_names[brand_name] = model_names except (ImportError, IOError): diff --git a/selfdrive/car/fingerprints.py b/selfdrive/car/fingerprints.py index b09e14a429ffb9..ed5892a0158360 100644 --- a/selfdrive/car/fingerprints.py +++ b/selfdrive/car/fingerprints.py @@ -11,7 +11,7 @@ def get_attr_from_cars(attr, result=dict, combine_brands=True): for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]: try: car_name = car_folder.split('/')[-1] - values = __import__('selfdrive.car.%s.values' % car_name, fromlist=[attr]) + values = __import__(f'selfdrive.car.{car_name}.values', fromlist=[attr]) if hasattr(values, attr): attr_values = getattr(values, attr) else: diff --git a/selfdrive/car/fw_versions.py b/selfdrive/car/fw_versions.py index 5d982d6a8df063..1c04f313e7bb00 100755 --- a/selfdrive/car/fw_versions.py +++ b/selfdrive/car/fw_versions.py @@ -362,7 +362,7 @@ def get_fw_versions(logcan, sendcan, bus, extra=None, timeout=0.1, debug=False, print("Getting vin...") addr, vin = get_vin(logcan, sendcan, 1, retry=10, debug=args.debug) print(f"VIN: {vin}") - print("Getting VIN took %.3f s" % (time.time() - t)) + print(f"Getting VIN took {time.time() - t:.3f} s") print() t = time.time() @@ -379,4 +379,4 @@ def get_fw_versions(logcan, sendcan, bus, extra=None, timeout=0.1, debug=False, print() print("Possible matches:", candidates) - print("Getting fw took %.3f s" % (time.time() - t)) + print(f"Getting fw took {time.time() - t:.3f} s") diff --git a/selfdrive/car/honda/interface.py b/selfdrive/car/honda/interface.py index 274f4ed5f63e9f..47bbd6715d2a13 100755 --- a/selfdrive/car/honda/interface.py +++ b/selfdrive/car/honda/interface.py @@ -301,7 +301,7 @@ def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=[]): # py ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.6], [0.18]] # TODO: can probably use some tuning else: - raise ValueError("unsupported car %s" % candidate) + raise ValueError(f"unsupported car {candidate}") # These cars use alternate user brake msg (0x1BE) if candidate in HONDA_BOSCH_ALT_BRAKE_SIGNAL: diff --git a/selfdrive/car/tests/test_car_interfaces.py b/selfdrive/car/tests/test_car_interfaces.py index 93dc05c8386561..930619ee6753de 100755 --- a/selfdrive/car/tests/test_car_interfaces.py +++ b/selfdrive/car/tests/test_car_interfaces.py @@ -59,7 +59,7 @@ def test_car_interfaces(self, car_name): car_interface.apply(CC) # Test radar interface - RadarInterface = importlib.import_module('selfdrive.car.%s.radar_interface' % car_params.carName).RadarInterface + RadarInterface = importlib.import_module(f'selfdrive.car.{car_params.carName}.radar_interface').RadarInterface radar_interface = RadarInterface(car_params) assert radar_interface diff --git a/selfdrive/car/volkswagen/interface.py b/selfdrive/car/volkswagen/interface.py index bef1c37185a519..b7346ebeaf4f1a 100644 --- a/selfdrive/car/volkswagen/interface.py +++ b/selfdrive/car/volkswagen/interface.py @@ -152,7 +152,7 @@ def get_params(candidate, fingerprint=gen_empty_fingerprint(), car_fw=None): ret.wheelbase = 2.84 else: - raise ValueError("unsupported car %s" % candidate) + raise ValueError(f"unsupported car {candidate}") ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase) ret.centerToFront = ret.wheelbase * 0.45 diff --git a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py index e0e0208d67f230..3a8234706fc34a 100644 --- a/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py +++ b/selfdrive/controls/lib/longitudinal_mpc_lib/long_mpc.py @@ -377,8 +377,7 @@ def run(self): if self.solution_status != 0: if t > self.last_cloudlog_t + 5.0: self.last_cloudlog_t = t - cloudlog.warning("Long mpc reset, solution_status: %s" % ( - self.solution_status)) + cloudlog.warning(f"Long mpc reset, solution_status: {self.solution_status}") self.reset() diff --git a/selfdrive/controls/lib/radar_helpers.py b/selfdrive/controls/lib/radar_helpers.py index 01498fa1388552..4f87fdf09bb163 100644 --- a/selfdrive/controls/lib/radar_helpers.py +++ b/selfdrive/controls/lib/radar_helpers.py @@ -146,7 +146,7 @@ def get_RadarState_from_vision(self, lead_msg, v_ego): } def __str__(self): - ret = "x: %4.1f y: %4.1f v: %4.1f a: %4.1f" % (self.dRel, self.yRel, self.vRel, self.aLeadK) + ret = f"x: {self.dRel:4.1f} y: {self.yRel:4.1f} v: {self.vRel:4.1f} a: {self.aLeadK:4.1f}" return ret def potential_low_speed_lead(self, v_ego): diff --git a/selfdrive/controls/radard.py b/selfdrive/controls/radard.py index 88f39ce4318538..14de2eff328cc9 100755 --- a/selfdrive/controls/radard.py +++ b/selfdrive/controls/radard.py @@ -189,7 +189,7 @@ def radard_thread(sm=None, pm=None, can_sock=None): # import the radar from the fingerprint cloudlog.info("radard is importing %s", CP.carName) - RadarInterface = importlib.import_module('selfdrive.car.%s.radar_interface' % CP.carName).RadarInterface + RadarInterface = importlib.import_module(f'selfdrive.car.{CP.carName}.radar_interface').RadarInterface # *** setup messaging if can_sock is None: diff --git a/selfdrive/controls/tests/test_alerts.py b/selfdrive/controls/tests/test_alerts.py index 920c126c447722..98767d6e2f0506 100755 --- a/selfdrive/controls/tests/test_alerts.py +++ b/selfdrive/controls/tests/test_alerts.py @@ -70,7 +70,7 @@ def test_alert_text_length(self): font = fonts[alert.alert_size][i] w, _ = draw.textsize(txt, font) - msg = "type: %s msg: %s" % (alert.alert_type, txt) + msg = f"type: {alert.alert_type} msg: {txt}" self.assertLessEqual(w, max_text_width, msg=msg) def test_alert_sanity_check(self): diff --git a/selfdrive/debug/can_printer.py b/selfdrive/debug/can_printer.py index cb6ff29006bdda..b4436bd2becdd8 100755 --- a/selfdrive/debug/can_printer.py +++ b/selfdrive/debug/can_printer.py @@ -22,7 +22,7 @@ def can_printer(bus, max_msg, addr): if sec_since_boot() - lp > 0.1: dd = chr(27) + "[2J" - dd += "%5.2f\n" % (sec_since_boot() - start) + dd += f"{sec_since_boot() - start:5.2f}\n" for addr in sorted(msgs.keys()): a = msgs[addr][-1].decode('ascii', 'backslashreplace') x = binascii.hexlify(msgs[addr][-1]).decode('ascii') diff --git a/selfdrive/debug/check_freq.py b/selfdrive/debug/check_freq.py index 300b3ea1fb133c..424ad67b6dcef8 100755 --- a/selfdrive/debug/check_freq.py +++ b/selfdrive/debug/check_freq.py @@ -42,6 +42,6 @@ for name in socket_names: dts = np.diff(rcv_times[name]) mean = np.mean(dts) - print("%s: Freq %.2f Hz, Min %.2f%%, Max %.2f%%, valid " % (name, 1.0 / mean, np.min(dts) / mean * 100, np.max(dts) / mean * 100), all(valids[name])) + print(f"{name}: Freq {1.0 / mean:.2f} Hz, Min {np.min(dts) / mean * 100:.2f}%, Max {np.max(dts) / mean * 100:.2f}%, valid ", all(valids[name])) prev_print = t diff --git a/selfdrive/debug/cpu_usage_stat.py b/selfdrive/debug/cpu_usage_stat.py index aafc696b464509..5f181e0a272e0d 100755 --- a/selfdrive/debug/cpu_usage_stat.py +++ b/selfdrive/debug/cpu_usage_stat.py @@ -110,10 +110,10 @@ def get_arg_parser(): stat['avg'][name] = (stat['avg'][name] * (i - c) + avg * c) / (i) stat['cpu_samples'][name] = [] - msg = 'avg: {1:.2%}, min: {2:.2%}, max: {3:.2%} {0}'.format(os.path.basename(k), stat['avg']['total'], stat['min']['total'], stat['max']['total']) + msg = f"avg: {stat['avg']['total']:.2%}, min: {stat['min']['total']:.2%}, max: {stat['max']['total']:.2%} {os.path.basename(k)}" if args.detailed_times: for stat_type in ['avg', 'min', 'max']: - msg += '\n {}: {}'.format(stat_type, [name + ':' + str(round(stat[stat_type][name]*100, 2)) for name in cpu_time_names]) + msg += f"\n {stat_type}: {[(name + ':' + str(round(stat[stat_type][name] * 100, 2))) for name in cpu_time_names]}" l.append((os.path.basename(k), stat['avg']['total'], msg)) l.sort(key=lambda x: -x[1]) for x in l: diff --git a/selfdrive/debug/dump.py b/selfdrive/debug/dump.py index 047c874fb777d9..f208920f129f95 100755 --- a/selfdrive/debug/dump.py +++ b/selfdrive/debug/dump.py @@ -54,13 +54,13 @@ elif args.dump_json: print(json.dumps(evt.to_dict())) elif values: - print("logMonotime = {}".format(evt.logMonoTime)) + print(f"logMonotime = {evt.logMonoTime}") for value in values: if hasattr(evt, value[0]): item = evt for key in value: item = getattr(item, key) - print("{} = {}".format(".".join(value), item)) + print(f"{'.'.join(value)} = {item}") print("") else: try: diff --git a/selfdrive/debug/get_fingerprint.py b/selfdrive/debug/get_fingerprint.py index 6c38957be32032..e678db4f178b5d 100755 --- a/selfdrive/debug/get_fingerprint.py +++ b/selfdrive/debug/get_fingerprint.py @@ -27,5 +27,5 @@ fingerprint = ', '.join("%d: %d" % v for v in sorted(msgs.items())) - print("number of messages {0}:".format(len(msgs))) - print("fingerprint {0}".format(fingerprint)) + print(f"number of messages {len(msgs)}:") + print(f"fingerprint {fingerprint}") diff --git a/selfdrive/debug/internal/power_monitor.py b/selfdrive/debug/internal/power_monitor.py index 3377088f8b1247..c995ef6ff2d8d6 100755 --- a/selfdrive/debug/internal/power_monitor.py +++ b/selfdrive/debug/internal/power_monitor.py @@ -45,7 +45,7 @@ def average(avg, sample): capacity_average = average(capacity_average, capacity) bat_temp_average = average(bat_temp_average, bat_temp) - print("%.2f volts %12.2f ma %12.2f mW %8.2f%% battery %8.1f degC" % (voltage, current, power, capacity, bat_temp)) + print(f"{voltage:.2f} volts {current:12.2f} ma {power:12.2f} mW {capacity:8.2f}% battery {bat_temp:8.1f} degC") time.sleep(0.1) finally: stop_time = datetime.now() @@ -55,8 +55,8 @@ def average(avg, sample): power = power_average[0] capacity = capacity_average[0] bat_temp = bat_temp_average[0] - print("%.2f volts %12.2f ma %12.2f mW %8.2f%% battery %8.1f degC" % (voltage, current, power, capacity, bat_temp)) - print(" {:.2f} Seconds {} samples".format((stop_time-start_time).total_seconds(), voltage_average[1])) + print(f"{voltage:.2f} volts {current:12.2f} ma {power:12.2f} mW {capacity:8.2f}% battery {bat_temp:8.1f} degC") + print(f" {(stop_time - start_time).total_seconds():.2f} Seconds {voltage_average[1]} samples") print("----------------------------------------------------------------") # reenable charging diff --git a/selfdrive/debug/live_cpu_and_temp.py b/selfdrive/debug/live_cpu_and_temp.py index 5589b0d6ddc8fe..e46c0b0a1f801d 100755 --- a/selfdrive/debug/live_cpu_and_temp.py +++ b/selfdrive/debug/live_cpu_and_temp.py @@ -71,7 +71,7 @@ def proc_name(proc): total_times = total_times_new[:] busy_times = busy_times_new[:] - print("CPU %.2f%% - RAM: %.2f%% - Temp %.2fC" % (100. * mean(cores), last_mem, last_temp)) + print(f"CPU {100.0 * mean(cores):.2f}% - RAM: {last_mem:.2f}% - Temp {last_temp:.2f}C") if args.cpu and prev_proclog is not None: procs = {} diff --git a/selfdrive/hardware/tici/power_monitor.py b/selfdrive/hardware/tici/power_monitor.py index 65f58876de63b7..d7f113cf2c5227 100755 --- a/selfdrive/hardware/tici/power_monitor.py +++ b/selfdrive/hardware/tici/power_monitor.py @@ -40,7 +40,7 @@ def average(avg, sample): power_average = average(power_average, power) power_total_average = average(power_total_average, power_total) - print("%12.2f mW %12.2f mW %12.2f mW" % (power, power_total, power_total-power)) + print(f"{power:12.2f} mW {power_total:12.2f} mW {power_total - power:12.2f} mW") time.sleep(0.25) finally: stop_time = time.monotonic() @@ -48,6 +48,6 @@ def average(avg, sample): voltage = voltage_average[0] current = current_average[0] power = power_average[0] - print("%.2f volts %12.2f ma %12.2f mW %12.2f mW" % (voltage, current, power, power_total)) - print(" {:.2f} Seconds {} samples".format(stop_time - start_time, voltage_average[1])) + print(f"{voltage:.2f} volts {current:12.2f} ma {power:12.2f} mW {power_total:12.2f} mW") + print(f" {stop_time - start_time:.2f} Seconds {voltage_average[1]} samples") print("----------------------------------------------------------------") diff --git a/selfdrive/loggerd/deleter.py b/selfdrive/loggerd/deleter.py index 16083ec921674a..e7006a08cfb2f2 100644 --- a/selfdrive/loggerd/deleter.py +++ b/selfdrive/loggerd/deleter.py @@ -27,11 +27,11 @@ def deleter_thread(exit_event): continue try: - cloudlog.info("deleting %s" % delete_path) + cloudlog.info(f"deleting {delete_path}") shutil.rmtree(delete_path) break except OSError: - cloudlog.exception("issue deleting %s" % delete_path) + cloudlog.exception(f"issue deleting {delete_path}") exit_event.wait(.1) else: exit_event.wait(30) diff --git a/selfdrive/loggerd/tools/mark_unuploaded.py b/selfdrive/loggerd/tools/mark_unuploaded.py index e219c3a53a680e..0d3f765af47674 100755 --- a/selfdrive/loggerd/tools/mark_unuploaded.py +++ b/selfdrive/loggerd/tools/mark_unuploaded.py @@ -4,5 +4,5 @@ from selfdrive.loggerd.uploader import UPLOAD_ATTR_NAME for fn in sys.argv[1:]: - print("unmarking %s" % fn) + print(f"unmarking {fn}") removexattr(fn, UPLOAD_ATTR_NAME) diff --git a/selfdrive/loggerd/uploader.py b/selfdrive/loggerd/uploader.py index 10bf218b03245c..c75b34e9cbde86 100644 --- a/selfdrive/loggerd/uploader.py +++ b/selfdrive/loggerd/uploader.py @@ -140,7 +140,7 @@ def do_upload(self, key, fn): cloudlog.debug("upload_url v1.4 %s %s", url, str(headers)) if fake_upload: - cloudlog.debug("*** WARNING, THIS IS A FAKE UPLOAD TO %s ***" % url) + cloudlog.debug(f"*** WARNING, THIS IS A FAKE UPLOAD TO {url} ***") class FakeResponse(): def __init__(self): diff --git a/selfdrive/manager/process.py b/selfdrive/manager/process.py index 22d75edce7830a..2030b35e32d4e6 100644 --- a/selfdrive/manager/process.py +++ b/selfdrive/manager/process.py @@ -39,7 +39,7 @@ def launcher(proc, name): # exec the process mod.main() except KeyboardInterrupt: - cloudlog.warning("child %s got SIGINT" % proc) + cloudlog.warning(f"child {proc} got SIGINT") except Exception: # can't install the crash handler because sys.excepthook doesn't play nice # with threads, so catch it here. @@ -194,7 +194,7 @@ def start(self): return cwd = os.path.join(BASEDIR, self.cwd) - cloudlog.info("starting process %s" % self.name) + cloudlog.info(f"starting process {self.name}") self.proc = Process(name=self.name, target=nativelauncher, args=(self.cmdline, cwd)) self.proc.start() self.watchdog_seen = False @@ -214,7 +214,7 @@ def __init__(self, name, module, enabled=True, persistent=False, driverview=Fals def prepare(self): if self.enabled: - cloudlog.info("preimporting %s" % self.module) + cloudlog.info(f"preimporting {self.module}") importlib.import_module(self.module) def start(self): @@ -225,7 +225,7 @@ def start(self): if self.proc is not None: return - cloudlog.info("starting python %s" % self.module) + cloudlog.info(f"starting python {self.module}") self.proc = Process(name=self.name, target=launcher, args=(self.module, self.name)) self.proc.start() self.watchdog_seen = False @@ -260,7 +260,7 @@ def start(self): # process is dead pass - cloudlog.info("starting daemon %s" % self.name) + cloudlog.info(f"starting daemon {self.name}") proc = subprocess.Popen(['python', '-m', self.module], # pylint: disable=subprocess-popen-preexec-fn stdin=open('/dev/null', 'r'), stdout=open('/dev/null', 'w'), diff --git a/selfdrive/modeld/visiontest.py b/selfdrive/modeld/visiontest.py index 8bf71d26d58c1c..1e30c05449a85e 100644 --- a/selfdrive/modeld/visiontest.py +++ b/selfdrive/modeld/visiontest.py @@ -62,7 +62,7 @@ def __init__(self, input_size, model_input_size, model): disable_model = 0 temporal_model = 1 else: - raise ValueError("Bad model name: {}".format(model)) + raise ValueError(f"Bad model name: {model}") prevdir = os.getcwd() os.chdir(_visiond_dir) # tmp hack to find kernels diff --git a/selfdrive/test/openpilotci.py b/selfdrive/test/openpilotci.py index 9cc0e37c4b2b7d..5bf43fb10a43c8 100755 --- a/selfdrive/test/openpilotci.py +++ b/selfdrive/test/openpilotci.py @@ -9,7 +9,7 @@ def get_url(route_name, segment_num, log_type="rlog"): ext = "hevc" if log_type in ["fcamera", "dcamera"] else "bz2" - return BASE_URL + "%s/%s/%s.%s" % (route_name.replace("|", "/"), segment_num, log_type, ext) + return BASE_URL + f"{route_name.replace('|', '/')}/{segment_num}/{log_type}.{ext}" def upload_file(path, name): from azure.storage.blob import BlockBlobService # pylint: disable=import-error diff --git a/selfdrive/test/process_replay/model_replay.py b/selfdrive/test/process_replay/model_replay.py index 13e0c7288ff4c3..6eb37dfa29e10a 100755 --- a/selfdrive/test/process_replay/model_replay.py +++ b/selfdrive/test/process_replay/model_replay.py @@ -31,7 +31,7 @@ def get_log_fn(ref_commit): - return "%s_%s_%s.bz2" % (TEST_ROUTE, "model_tici" if TICI else "model", ref_commit) + return f"{TEST_ROUTE}_{'model_tici' if TICI else 'model'}_{ref_commit}.bz2" def replace_calib(msg, calib): diff --git a/selfdrive/test/process_replay/test_processes.py b/selfdrive/test/process_replay/test_processes.py index 8fd1b0b42180ba..3283ec81910576 100755 --- a/selfdrive/test/process_replay/test_processes.py +++ b/selfdrive/test/process_replay/test_processes.py @@ -74,7 +74,7 @@ def test_process(cfg, lr, cmp_log_fn, ignore_fields=None, ignore_msgs=None): break else: segment = cmp_log_fn.split("/")[-1].split("_")[0] - raise Exception("Route never enabled: %s" % segment) + raise Exception(f"Route never enabled: {segment}") try: return compare_logs(cmp_log_msgs, log_msgs, ignore_fields+cfg.ignore, ignore_msgs, cfg.tolerance) @@ -83,30 +83,30 @@ def test_process(cfg, lr, cmp_log_fn, ignore_fields=None, ignore_msgs=None): def format_diff(results, ref_commit): diff1, diff2 = "", "" - diff2 += "***** tested against commit %s *****\n" % ref_commit + diff2 += f"***** tested against commit {ref_commit} *****\n" failed = False for segment, result in list(results.items()): - diff1 += "***** results for segment %s *****\n" % segment - diff2 += "***** differences for segment %s *****\n" % segment + diff1 += f"***** results for segment {segment} *****\n" + diff2 += f"***** differences for segment {segment} *****\n" for proc, diff in list(result.items()): - diff1 += "\t%s\n" % proc - diff2 += "*** process: %s ***\n" % proc + diff1 += f"\t{proc}\n" + diff2 += f"*** process: {proc} ***\n" if isinstance(diff, str): - diff1 += "\t\t%s\n" % diff + diff1 += f"\t\t{diff}\n" failed = True elif len(diff): cnt = {} for d in diff: - diff2 += "\t%s\n" % str(d) + diff2 += f"\t{str(d)}\n" k = str(d[1]) cnt[k] = 1 if k not in cnt else cnt[k] + 1 for k, v in sorted(cnt.items()): - diff1 += "\t\t%s: %s\n" % (k, v) + diff1 += f"\t\t{k}: {v}\n" failed = True return diff1, diff2, failed @@ -139,13 +139,13 @@ def format_diff(results, ref_commit): print("couldn't find reference commit") sys.exit(1) - print("***** testing against commit %s *****" % ref_commit) + print(f"***** testing against commit {ref_commit} *****") # check to make sure all car brands are tested if FULL_TEST: tested_cars = set(c.lower() for c, _ in segments) untested = (set(interface_names) - set(excluded_interfaces)) - tested_cars - assert len(untested) == 0, "Cars missing routes: %s" % (str(untested)) + assert len(untested) == 0, f"Cars missing routes: {str(untested)}" results: Any = {} for car_brand, segment in segments: @@ -153,7 +153,7 @@ def format_diff(results, ref_commit): (not cars_whitelisted and car_brand.upper() in args.blacklist_cars): continue - print("***** testing route segment %s *****\n" % segment) + print(f"***** testing route segment {segment} *****\n") results[segment] = {} @@ -165,7 +165,7 @@ def format_diff(results, ref_commit): (not procs_whitelisted and cfg.proc_name in args.blacklist_procs): continue - cmp_log_fn = os.path.join(process_replay_dir, "%s_%s_%s.bz2" % (segment, cfg.proc_name, ref_commit)) + cmp_log_fn = os.path.join(process_replay_dir, f"{segment}_{cfg.proc_name}_{ref_commit}.bz2") results[segment][cfg.proc_name] = test_process(cfg, lr, cmp_log_fn, args.ignore_fields, args.ignore_msgs) diff1, diff2, failed = format_diff(results, ref_commit) diff --git a/selfdrive/test/process_replay/update_refs.py b/selfdrive/test/process_replay/update_refs.py index 96feb0d534fa89..0a3d95e7146f2b 100755 --- a/selfdrive/test/process_replay/update_refs.py +++ b/selfdrive/test/process_replay/update_refs.py @@ -28,7 +28,7 @@ for cfg in CONFIGS: log_msgs = replay_process(cfg, lr) - log_fn = os.path.join(process_replay_dir, "%s_%s_%s.bz2" % (segment, cfg.proc_name, ref_commit)) + log_fn = os.path.join(process_replay_dir, f"{segment}_{cfg.proc_name}_{ref_commit}.bz2") save_log(log_fn, log_msgs) if not no_upload: diff --git a/selfdrive/test/test_fingerprints.py b/selfdrive/test/test_fingerprints.py index 07e47748271cdc..96bb5ffa02faff 100755 --- a/selfdrive/test/test_fingerprints.py +++ b/selfdrive/test/test_fingerprints.py @@ -18,7 +18,7 @@ def _get_fingerprints(): for car_folder in [x[0] for x in os.walk(BASEDIR + '/selfdrive/car')]: car_name = car_folder.split('/')[-1] try: - fingerprints[car_name] = __import__('selfdrive.car.%s.values' % car_name, fromlist=['FINGERPRINTS']).FINGERPRINTS + fingerprints[car_name] = __import__(f'selfdrive.car.{car_name}.values', fromlist=['FINGERPRINTS']).FINGERPRINTS except (ImportError, IOError, AttributeError): pass @@ -80,14 +80,14 @@ def check_can_ignition_conflicts(fingerprints, brands): for idx2, f2 in enumerate(fingerprints_flat): if idx1 < idx2 and not check_fingerprint_consistency(f1, f2): valid = False - print("Those two fingerprints are inconsistent {0} {1}".format(car_names[idx1], car_names[idx2])) + print(f"Those two fingerprints are inconsistent {car_names[idx1]} {car_names[idx2]}") print("") print(', '.join("%d: %d" % v for v in sorted(f1.items()))) print("") print(', '.join("%d: %d" % v for v in sorted(f2.items()))) print("") - print("Found {0} individual fingerprints".format(len(fingerprints_flat))) + print(f"Found {len(fingerprints_flat)} individual fingerprints") if not valid or len(fingerprints_flat) == 0: print("TEST FAILED") sys.exit(1) diff --git a/selfdrive/test/test_models.py b/selfdrive/test/test_models.py index 5c277bfcb12f98..5112d3091917b7 100755 --- a/selfdrive/test/test_models.py +++ b/selfdrive/test/test_models.py @@ -134,7 +134,7 @@ def test_car_interface(self): def test_radar_interface(self): os.environ['NO_RADAR_SLEEP'] = "1" - RadarInterface = importlib.import_module('selfdrive.car.%s.radar_interface' % self.CP.carName).RadarInterface + RadarInterface = importlib.import_module(f'selfdrive.car.{self.CP.carName}.radar_interface').RadarInterface RI = RadarInterface(self.CP) assert RI diff --git a/selfdrive/test/update_ci_routes.py b/selfdrive/test/update_ci_routes.py index 3e5a0d2cf0db24..3a392b4b36a749 100755 --- a/selfdrive/test/update_ci_routes.py +++ b/selfdrive/test/update_ci_routes.py @@ -25,7 +25,7 @@ def upload_route(path): "azcopy", "copy", f"{path}/*", - "https://{}.blob.core.windows.net/{}/{}?{}".format(_DATA_ACCOUNT_CI, "openpilotci", destpath, DEST_KEY), + f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{destpath}?{DEST_KEY}", "--recursive=false", "--overwrite=false", "--exclude-pattern=*/dcamera.hevc", @@ -46,8 +46,8 @@ def sync_to_ci_public(route): cmd = [ "azcopy", "copy", - "https://{}.blob.core.windows.net/{}/{}?{}".format(source_account, source_bucket, key_prefix, source_key), - "https://{}.blob.core.windows.net/{}/{}?{}".format(_DATA_ACCOUNT_CI, "openpilotci", dongle_id, DEST_KEY), + f"https://{source_account}.blob.core.windows.net/{source_bucket}/{key_prefix}?{source_key}", + f"https://{_DATA_ACCOUNT_CI}.blob.core.windows.net/openpilotci/{dongle_id}?{DEST_KEY}", "--recursive=true", "--overwrite=false", "--exclude-pattern=*/dcamera.hevc", diff --git a/selfdrive/updated.py b/selfdrive/updated.py index 2aa8147dae974f..eaaed0e8de6483 100755 --- a/selfdrive/updated.py +++ b/selfdrive/updated.py @@ -342,7 +342,7 @@ def fetch_update(wait_helper: WaitTimeHelper) -> bool: new_version = cur_hash != upstream_hash git_fetch_result = check_git_fetch_result(git_fetch_output) - cloudlog.info("comparing %s to %s" % (cur_hash, upstream_hash)) + cloudlog.info(f"comparing {cur_hash} to {upstream_hash}") if new_version or git_fetch_result: cloudlog.info("Running update") diff --git a/selfdrive/version.py b/selfdrive/version.py index 6f15228d8b55d1..a0cb61875e58a5 100644 --- a/selfdrive/version.py +++ b/selfdrive/version.py @@ -115,9 +115,9 @@ def is_dirty() -> bool: params.put("TermsVersion", terms_version) params.put("TrainingVersion", training_version) - print("Dirty: %s" % is_dirty()) - print("Version: %s" % get_version()) - print("Origin: %s" % get_origin()) - print("Branch: %s" % get_branch()) - print("Short branch: %s" % get_short_branch()) - print("Prebuilt: %s" % is_prebuilt()) + print(f"Dirty: {is_dirty()}") + print(f"Version: {get_version()}") + print(f"Origin: {get_origin()}") + print(f"Branch: {get_branch()}") + print(f"Short branch: {get_short_branch()}") + print(f"Prebuilt: {is_prebuilt()}") diff --git a/tools/lib/framereader.py b/tools/lib/framereader.py index db07c20177f63b..bd7980f6e0d68c 100644 --- a/tools/lib/framereader.py +++ b/tools/lib/framereader.py @@ -50,7 +50,7 @@ def fingerprint_video(fn): with FileReader(fn) as f: header = f.read(4) if len(header) == 0: - raise DataUnreadableError("%s is empty" % fn) + raise DataUnreadableError(f"{fn} is empty") elif header == b"\x00\xc0\x12\x00": return FrameType.raw elif header == b"\x00\x00\x00\x01": @@ -90,7 +90,7 @@ def vidindex(fn, typ): try: subprocess.check_call([vidindex, typ, fn, prefix_f.name, index_f.name]) except subprocess.CalledProcessError: - raise DataUnreadableError("vidindex failed on file %s" % fn) + raise DataUnreadableError(f"vidindex failed on file {fn}") with open(index_f.name, "rb") as f: index = f.read() with open(prefix_f.name, "rb") as f: @@ -308,7 +308,7 @@ def get(self, num, count=1, pix_fmt="yuv420p"): assert num+count <= self.frame_count if pix_fmt not in ("yuv420p", "rgb24"): - raise ValueError("Unsupported pixel format %r" % pix_fmt) + raise ValueError(f"Unsupported pixel format {pix_fmt!r}") app = [] for i in range(num, num+count): @@ -548,10 +548,10 @@ def get(self, num, count=1, pix_fmt="yuv420p"): assert self.frame_count is not None if num + count > self.frame_count: - raise ValueError("{} > {}".format(num + count, self.frame_count)) + raise ValueError(f"{num + count} > {self.frame_count}") if pix_fmt not in ("yuv420p", "rgb24", "yuv444p"): - raise ValueError("Unsupported pixel format %r" % pix_fmt) + raise ValueError(f"Unsupported pixel format {pix_fmt!r}") ret = [self._get_one(num + i, pix_fmt) for i in range(count)] diff --git a/tools/lib/route.py b/tools/lib/route.py index 8c03cd9ccaf2bf..76ca2bcf5487df 100644 --- a/tools/lib/route.py +++ b/tools/lib/route.py @@ -112,7 +112,7 @@ def _get_segments_local(self, data_dir): if not seg_num.isdigit(): continue - segment_name = '{}--{}'.format(self.route_name, seg_num) + segment_name = f'{self.route_name}--{seg_num}' for seg_f in os.listdir(os.path.join(fullpath, seg_num)): segment_files[segment_name].append((os.path.join(fullpath, seg_num, seg_f), seg_f)) @@ -152,7 +152,7 @@ def _get_segments_local(self, data_dir): segments.append(RouteSegment(segment, log_path, qlog_path, camera_path, dcamera_path, ecamera_path, qcamera_path)) if len(segments) == 0: - raise ValueError('Could not find segments for route {} in data directory {}'.format(self.route_name, data_dir)) + raise ValueError(f'Could not find segments for route {self.route_name} in data directory {data_dir}') return sorted(segments, key=lambda seg: seg.canonical_name.segment_num) class RouteSegment(object): diff --git a/tools/lib/url_file.py b/tools/lib/url_file.py index 2161770d030409..82f7c971fce0ef 100644 --- a/tools/lib/url_file.py +++ b/tools/lib/url_file.py @@ -156,7 +156,7 @@ def test(debug_type, debug_msg): if self._debug: t2 = time.time() if t2 - t1 > 0.1: - print("get %s %r %.f slow" % (self._url, headers, t2 - t1)) + print(f"get {self._url} {headers!r} {t2 - t1:.f} slow") response_code = c.getinfo(pycurl.RESPONSE_CODE) if response_code == 416: # Requested Range Not Satisfiable diff --git a/tools/replay/lib/ui_helpers.py b/tools/replay/lib/ui_helpers.py index 0573973f9f2ccc..7410c107c4be05 100644 --- a/tools/replay/lib/ui_helpers.py +++ b/tools/replay/lib/ui_helpers.py @@ -152,7 +152,7 @@ def init_plots(arr, name_to_arr_idx, plot_xlims, plot_ylims, plot_names, plot_co plots.append(plot) idxs.append(name_to_arr_idx[item]) plot_select.append(i) - axs[i].set_title(", ".join("%s (%s)" % (nm, cl) + axs[i].set_title(", ".join(f"{nm} ({cl})" for (nm, cl) in zip(pl_list, plot_colors[i])), fontsize=10) axs[i].tick_params(axis="x", colors="white") axs[i].tick_params(axis="y", colors="white") diff --git a/tools/scripts/fetch_image_from_route.py b/tools/scripts/fetch_image_from_route.py index e9111d9de2860a..39751ba55123d0 100755 --- a/tools/scripts/fetch_image_from_route.py +++ b/tools/scripts/fetch_image_from_route.py @@ -2,7 +2,7 @@ import sys if len(sys.argv) < 4: - print("%s " % sys.argv[0]) + print(f"{sys.argv[0]} ") print('example: ./fetch_image_from_route.py "02c45f73a2e5c6e9|2020-06-01--18-03-08" 3 500') exit(0) @@ -33,5 +33,5 @@ im = Image.fromarray(fr.get(frame, count=1, pix_fmt="rgb24")[0]) fn = "uxxx_"+route.replace("|", "_")+"_%d_%d.png" % (segment, frame) im.save(fn) -print("saved %s" % fn) +print(f"saved {fn}") diff --git a/tools/scripts/save_ubloxraw_stream.py b/tools/scripts/save_ubloxraw_stream.py index 518c4ecaf635ee..b04826a5dbe75a 100644 --- a/tools/scripts/save_ubloxraw_stream.py +++ b/tools/scripts/save_ubloxraw_stream.py @@ -52,7 +52,7 @@ def main(argv): i += 1 except StopIteration: print('All done') - print('Writed {} msgs'.format(i)) + print(f'Writed {i} msgs') if __name__ == "__main__": diff --git a/tools/scripts/setup_ssh_keys.py b/tools/scripts/setup_ssh_keys.py index 0eb44dbd59b571..5b5ebfbac5b68b 100755 --- a/tools/scripts/setup_ssh_keys.py +++ b/tools/scripts/setup_ssh_keys.py @@ -7,7 +7,7 @@ if __name__ == "__main__": if len(sys.argv) < 2: - print("%s " % sys.argv[0]) + print(f"{sys.argv[0]} ") exit(1) username = sys.argv[1] diff --git a/tools/sim/lib/manual_ctrl.py b/tools/sim/lib/manual_ctrl.py index d2111ad1503ce9..7c47e2ba4a07d3 100755 --- a/tools/sim/lib/manual_ctrl.py +++ b/tools/sim/lib/manual_ctrl.py @@ -10,7 +10,7 @@ print('Available devices:') for fn in os.listdir('/dev/input'): if fn.startswith('js'): - print(' /dev/input/%s' % (fn)) + print(f' /dev/input/{fn}') # We'll store the states here. axis_states = {} @@ -94,7 +94,7 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: # Open the joystick device. fn = '/dev/input/js0' - print('Opening %s...' % fn) + print(f'Opening {fn}...') jsdev = open(fn, 'rb') # Get the device name. @@ -102,7 +102,7 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: buf = array.array('B', [0] * 64) ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len) js_name = buf.tobytes().rstrip(b'\x00').decode('utf-8') - print('Device name: %s' % js_name) + print(f'Device name: {js_name}') # Get number of axes and buttons. buf = array.array('B', [0]) @@ -118,7 +118,7 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP for _axis in buf[:num_axes]: - axis_name = axis_names.get(_axis, 'unknown(0x%02x)' % _axis) + axis_name = axis_names.get(_axis, f'unknown(0x{_axis:02x})') axis_map.append(axis_name) axis_states[axis_name] = 0.0 @@ -127,7 +127,7 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP for btn in buf[:num_buttons]: - btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn) + btn_name = button_names.get(btn, f'unknown(0x{btn:03x})') button_map.append(btn_name) button_states[btn_name] = 0 @@ -153,19 +153,19 @@ def wheel_poll_thread(q: 'Queue[str]') -> NoReturn: fvalue = value / 32767.0 axis_states[axis] = fvalue normalized = (1 - fvalue) * 50 - q.put("throttle_%f" % normalized) + q.put(f"throttle_{normalized:f}") elif axis == "rz": # brake fvalue = value / 32767.0 axis_states[axis] = fvalue normalized = (1 - fvalue) * 50 - q.put("brake_%f" % normalized) + q.put(f"brake_{normalized:f}") elif axis == "x": # steer angle fvalue = value / 32767.0 axis_states[axis] = fvalue normalized = fvalue - q.put("steer_%f" % normalized) + q.put(f"steer_{normalized:f}") elif mtype & 0x01: # buttons if value == 1: # press down