Skip to content

Commit 3fec9b1

Browse files
Use f-strings in Python scripts
1 parent c818294 commit 3fec9b1

File tree

3 files changed

+29
-29
lines changed

3 files changed

+29
-29
lines changed

libcpuid/check-consistency.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
err = 0
1111
def getEnumElements(enumName):
12-
f = open("%s/libcpuid.h" % args.root_dir, "r")
12+
f = open(f"{args.root_dir}/libcpuid.h", "r")
1313
l = []
1414
on = False
1515
rexp = re.compile(r'^\s*([A-Z0-9_]+)(\s*=\s*[A-Z0-9_]+)?\s*,.*$')
@@ -28,7 +28,7 @@ def getEnumElements(enumName):
2828
return []
2929

3030
def getConstant(constantName):
31-
f = open("%s/libcpuid_constants.h" % args.root_dir, "r")
31+
f = open(f"{args.root_dir}/libcpuid_constants.h", "r")
3232
value = 0
3333
for line in f:
3434
items = line.strip().split()
@@ -38,10 +38,10 @@ def getConstant(constantName):
3838
return value
3939

4040
def checkEnumSize(enumName, constantName):
41-
print("Checking enum `%s':" % enumName, end=' ')
41+
print(f"Checking enum `{enumName}':", end=' ')
4242
count = len(getEnumElements(enumName)) - 1
4343
themax = getConstant(constantName)
44-
print("%d elements; max size (%s=%d)..." % (count, constantName, themax), end=' ')
44+
print(f"{count} elements; max size ({constantName}={themax})...", end=' ')
4545
if count > themax:
4646
err += 1
4747
print("FAILED")
@@ -70,7 +70,7 @@ def check_type_directory(directory):
7070

7171
rexp = re.compile('.*{ CPU_FEATURE_([^,]+), "([^"]+)".*}.*')
7272
print("Finding features:")
73-
for fn in glob.glob("%s/*.c" % args.root_dir):
73+
for fn in glob.glob(f"{args.root_dir}/*.c"):
7474
f = open(fn, "rt")
7575
line = 1
7676
nfeat = 0
@@ -81,16 +81,16 @@ def check_type_directory(directory):
8181
assert len(res) == 1, "Too many matches"
8282
if res[0][0].lower() != res[0][1]:
8383
err += 1
84-
print("..Mismatch - %s:%d - `%s' vs `%s'" % (os.path.basename(fn), line, res[0][0], res[0][1]))
84+
print(f"..Mismatch - {os.path.basename(fn)}:{line} - `{res[0][0]}' vs `{res[0][1]}'")
8585
line += 1
8686
if nfeat:
87-
print(" %s: %d features described" % (os.path.basename(fn), nfeat))
87+
print(f" {os.path.basename(fn)}: {nfeat} features described")
8888
f.close()
8989

9090
# Check whether all features are converted by cpu_feature_str():
9191

9292
allf = []
93-
f = open("%s/libcpuid.h" % args.root_dir, "rt")
93+
f = open(f"{args.root_dir}/libcpuid.h", "rt")
9494
rexp = re.compile('\t(CPU_FEATURE_[^, ]+).*')
9595
for s in f.readlines():
9696
if rexp.match(s):
@@ -100,22 +100,22 @@ def check_type_directory(directory):
100100

101101
impf = []
102102
rexp = re.compile('\t+{ (CPU_FEATURE_[^,]+).*')
103-
f = open("%s/cpuid_main.c" % args.root_dir, "rt")
103+
f = open(f"{args.root_dir}/cpuid_main.c", "rt")
104104
for s in f.readlines():
105105
if rexp.match(s):
106106
entry = rexp.findall(s)[0]
107107
if entry in impf:
108108
err += 1
109-
print("cpu_feature_str(): duplicate entry: %s" % entry)
109+
print(f"cpu_feature_str(): duplicate entry: {entry}")
110110
impf.append(entry)
111111
f.close()
112112

113-
print("Found %d total features and %d named features" % (len(allf), len(impf)))
113+
print(f"Found {len(allf)} total features and {len(impf)} named features")
114114

115115
for feature in allf:
116116
if not feature in impf:
117117
err += 1
118-
print("cpu_feature_str(): don't have entry for %s" % feature)
118+
print(f"cpu_feature_str(): don't have entry for {feature}")
119119

120120
# Check whether all features have detection code:
121121
print("Checking whether all features have detection code...", end=' ')
@@ -127,7 +127,7 @@ def check_type_directory(directory):
127127
rexp2 = re.compile(r'.*(CPU_FEATURE_[^ ,]+),\s*FEATURE_LEVEL_ARM_.*') # e.g. "set_feature_status(data, ext_status, (mte_frac == 0b0000), CPU_FEATURE_MTE_ASYNC, FEATURE_LEVEL_ARM_V8_5_A, -1);"
128128
rexp3 = re.compile(r'.*(CPU_FEATURE_[^ }]+).*') # e.g. "{ 28, CPU_FEATURE_HT },"
129129

130-
for fn in glob.glob("%s/*.c" % args.root_dir):
130+
for fn in glob.glob(f"{args.root_dir}/*.c"):
131131
f = open(fn, "rt")
132132
files_code[fn] = []
133133
for s in f.readlines():
@@ -157,13 +157,13 @@ def check_type_directory(directory):
157157
print("FAILED:")
158158
firstError = False
159159
err += 1
160-
print("..No detection code for %s" % feature)
160+
print(f"..No detection code for {feature}")
161161
if len(matching_files) > 1 and feature not in features_whitelist:
162162
if firstError:
163163
print("FAILED:")
164164
firstError = False
165165
err += 1
166-
print("..Conflicting detection code for %s in files %s" % (feature, " and ".join(matching_files)))
166+
print(f"..Conflicting detection code for {feature} in files {" and ".join(matching_files)}")
167167

168168
if firstError:
169169
print("All OK.")
@@ -178,7 +178,7 @@ def check_type_directory(directory):
178178
match_entry_fields = 11 # this number needs to change if the definition of match_entry_t ever changes
179179
codename_str_max = 64-1 # this number needs to change if the value of CODENAME_STR_MAX ever changes
180180
common_cache_sizes = ["8", "16", "32", "64", "128", "256", "512", "1024", "2048", "3072", "4096", "6144", "8192", "12288", "16384"]
181-
for fn in glob.glob("%s/*.c" % args.root_dir):
181+
for fn in glob.glob(f"{args.root_dir}/*.c"):
182182
bfn = os.path.basename(fn)
183183
nline = 0
184184
f = open(fn, "rt")
@@ -202,23 +202,23 @@ def check_type_directory(directory):
202202
s = parts[match_entry_fields-1].strip()
203203
if s[0] != '"' or s[-1] != '"':
204204
err += 1
205-
print("..Warning, %s:%d - cannot correctly handle the cpu codename" % (bfn, nline))
205+
print(f"..Warning, {bfn}:{nline} - cannot correctly handle the cpu codename")
206206
allok = False
207207
continue
208208
s = s[1:-1]
209209
if len(s) > codename_str_max:
210210
err += 1
211-
print("..%s:%d - codename (%s) is longer than %d characters!" % (bfn, nline, s, codename_str_max))
211+
print(f"..{bfn}:{nline} - codename ({s}) is longer than {codename_str_max} characters!")
212212
allok = False
213213
if cache_exp.match(s):
214214
cache_size = cache_exp.findall(s)[0][1:-1]
215215
if not cache_size in common_cache_sizes:
216216
err += 1
217-
print("..Warning, %s:%d - suspicious cache size in codename [%s] (%s)" % (bfn, nline, s, cache_size))
217+
print(f"..Warning, {bfn}:{nline} - suspicious cache size in codename [{s}] ({cache_size})")
218218
allok = False
219219
if cdefs:
220220
definitions += 1
221-
print(" %s: %d processor definitions," % (bfn, cdefs), end=' ')
221+
print(f" {bfn}: {cdefs} processor definitions,", end=' ')
222222
if allok:
223223
print("all OK")
224224
else:

tests/create_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def readResultFile():
4949
if field in numeric:
5050
value = s[s.find(":")+1:].strip()
5151
if not rexp.match(value):
52-
raise "Bad format of value: [%s]" % s
52+
raise f"Bad format of value: [{s}]"
5353
repdata.append(rexp.findall(value)[0])
5454
if "CPU Info for type" in field:
5555
repdata.append(delimiter)

tests/run_tests.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def make_tempname(prefix):
3434
return prefix
3535

3636
def fmt_error(err):
37-
pfix = " %s: " % err[0]
38-
return "%sexpected `%s'\n%sgot `%s'" % (pfix, err[1], " "*len(pfix), err[2])
37+
pfix = f" {err[0]}: "
38+
return f"{pfix} expected `{err[1]}'\n{" "*len(pfix)} got `{err[2]}'"
3939

4040
def fixFile(filename, input_lines, output_lines):
4141
f = open(filename, "wt")
@@ -50,14 +50,14 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
5050
f = open(fninp, "wt")
5151
f.writelines([s + "\n" for s in inp])
5252
f.close()
53-
architecture = os.popen("%s --load=%s --architecture" % (binary, fninp)).read().splitlines()[-1]
53+
architecture = os.popen(f"{binary} --load={fninp} --architecture").read().splitlines()[-1]
5454
if architecture == "x86":
5555
fields = fields_x86
5656
elif architecture == "ARM":
5757
fields = fields_arm
5858
else:
5959
fields = []
60-
cmd = "%s --load=%s --outfile=%s %s" % (binary, fninp, fnoutp, " ".join(["--" + s for s in fields]))
60+
cmd = f"{binary} --load={fninp} --outfile={fnoutp} {" ".join(["--" + s for s in fields])}"
6161
os.system(cmd)
6262
os.unlink(fninp)
6363
real_out = []
@@ -77,7 +77,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
7777
fixFile(test_file_name, inp, real_out_delim)
7878
return "Number of records, fixed."
7979
else:
80-
return "Unexpected number of records returned\n - expected length %d\n - real length %d\n - %d fields" % (len(expected_out), len(real_out), len(fields) * num_cpu_type)
80+
return f"Unexpected number of records returned\n - expected length {len(expected_out)}\n - real length {len(real_out)}\n - {len(fields) * num_cpu_type} fields"
8181
err_fields = []
8282
for i in range(len(real_out)):
8383
if real_out[i] != expected_out[i]:
@@ -89,7 +89,7 @@ def do_test(inp, expected_out, binary, test_file_name, num_cpu_type):
8989
fixFile(test_file_name, inp, real_out_delim)
9090
return "Mismatch, fixed."
9191
else:
92-
return "Mismatch in fields:\n%s" % "\n".join([fmt_error(err) for err in err_fields])
92+
return f"Mismatch in fields:\n{"\n".join([fmt_error(err) for err in err_fields])}"
9393

9494
def is_regular_file(filename):
9595
try:
@@ -161,7 +161,7 @@ def check_type_binary_file(filename):
161161
if test_file_name.suffixes[1] == ".xz":
162162
f = lzma.open(test_file_name, "rt")
163163
else:
164-
print("Test [%s]: skipped because %s is not supported" % (test_file_name.name, "".join(test_file_name.suffixes[1:])))
164+
print(f"Test [{test_file_name.name}]: skipped because {"".join(test_file_name.suffixes[1:])} is not supported")
165165
continue
166166
else:
167167
# Plain text file
@@ -180,7 +180,7 @@ def check_type_binary_file(filename):
180180
f.close()
181181
#codename = current_output[len(current_output) - 2]
182182
result = do_test(current_input, current_output, args.cpuid_tool, test_file_name, num_cpu_type)
183-
print("Test [%s]: %s" % (test_file_name.name, result))
183+
print(f"Test [{test_file_name.name}]: {result}")
184184
if result != "OK":
185185
errors = True
186186
build_output = False

0 commit comments

Comments
 (0)