Skip to content

Commit

Permalink
Use str.format() instead of % (#2485)
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo authored Dec 20, 2024
1 parent c3effb7 commit 304f08f
Show file tree
Hide file tree
Showing 20 changed files with 85 additions and 76 deletions.
4 changes: 2 additions & 2 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ def get_proc_inodes(self, pid):
inode = readlink(f"{self._procfs_path}/{pid}/fd/{fd}")
except (FileNotFoundError, ProcessLookupError):
# ENOENT == file which is gone in the meantime;
# os.stat('/proc/%s' % self.pid) will be done later
# os.stat(f"/proc/{self.pid}") will be done later
# to force NSP (if it's the case)
continue
except OSError as err:
Expand Down Expand Up @@ -2113,7 +2113,7 @@ def threads(self):

@wrap_exceptions
def nice_get(self):
# with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
# with open_text(f"{self._procfs_path}/{self.pid}/stat") as f:
# data = f.read()
# return int(data.split()[18])

Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1367,7 +1367,7 @@ def print_sysinfo():

print("=" * 70, file=sys.stderr) # NOQA
for k, v in info.items():
print("%-17s %s" % (k + ':', v), file=sys.stderr) # NOQA
print("{:<17} {}".format(k + ":", v), file=sys.stderr) # noqa: T201
print("=" * 70, file=sys.stderr) # NOQA
sys.stdout.flush()

Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,7 +976,7 @@ def test_ips(self):
# found += 1
# name = line.split(':')[1].strip()
# self.assertIn(name, nics)
# self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
# self.assertEqual(len(nics), found, msg="{}\n---\n{}".format(
# pprint.pformat(nics), out))


Expand Down
9 changes: 5 additions & 4 deletions psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,8 +416,9 @@ def test_cpu_times(self):
# for field in new._fields:
# new_t = getattr(new, field)
# last_t = getattr(last, field)
# self.assertGreaterEqual(new_t, last_t,
# msg="%s %s" % (new_t, last_t))
# self.assertGreaterEqual(
# new_t, last_t,
# msg="{} {}".format(new_t, last_t))
# last = new

def test_cpu_times_time_increases(self):
Expand Down Expand Up @@ -461,7 +462,7 @@ def test_per_cpu_times(self):
# new_t = getattr(newcpu, field)
# last_t = getattr(lastcpu, field)
# self.assertGreaterEqual(
# new_t, last_t, msg="%s %s" % (lastcpu, newcpu))
# new_t, last_t, msg="{} {}".format(lastcpu, newcpu))
# last = new

def test_per_cpu_times_2(self):
Expand Down Expand Up @@ -493,7 +494,7 @@ def test_cpu_times_comparison(self):
with self.subTest(field=field, base=base, per_cpu=per_cpu):
assert (
abs(getattr(base, field) - getattr(summed_values, field))
< 1
< 1.5
)

def _test_cpu_percent(self, percent, last_ret, new_ret):
Expand Down
10 changes: 7 additions & 3 deletions scripts/disk_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@


def main():
templ = "%-17s %8s %8s %8s %5s%% %9s %s"
print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
templ = "{:<17} {:>8} {:>8} {:>8} {:>5}% {:>9} {}"
print(
templ.format(
"Device", "Total", "Used", "Free", "Use ", "Type", "Mount"
)
)
for part in psutil.disk_partitions(all=False):
if os.name == 'nt':
if 'cdrom' in part.opts or not part.fstype:
Expand All @@ -33,7 +37,7 @@ def main():
# partition or just hang.
continue
usage = psutil.disk_usage(part.mountpoint)
line = templ % (
line = templ.format(
part.device,
bytes2human(usage.total),
bytes2human(usage.used),
Expand Down
10 changes: 6 additions & 4 deletions scripts/free.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
def main():
virt = psutil.virtual_memory()
swap = psutil.swap_memory()
templ = "%-7s %10s %10s %10s %10s %10s %10s"
print(templ % ('', 'total', 'used', 'free', 'shared', 'buffers', 'cache'))
sect = templ % (
templ = "{:<7} {:>10} {:>10} {:>10} {:>10} {:>10} {:>10}"
print(
templ.format("", "total", "used", "free", "shared", "buffers", "cache")
)
sect = templ.format(
'Mem:',
int(virt.total / 1024),
int(virt.used / 1024),
Expand All @@ -30,7 +32,7 @@ def main():
int(getattr(virt, 'cached', 0) / 1024),
)
print(sect)
sect = templ % (
sect = templ.format(
'Swap:',
int(swap.total / 1024),
int(swap.used / 1024),
Expand Down
6 changes: 3 additions & 3 deletions scripts/internal/print_access_denied.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ def main():
elapsed = time.time() - start

# print
templ = "%-20s %-5s %-9s %s"
s = templ % ("API", "AD", "Percent", "Outcome")
templ = "{:<20} {:<5} {:<9} {}"
s = templ.format("API", "AD", "Percent", "Outcome")
print_color(s, color=None, bold=True)
for methname, ads in sorted(d.items(), key=lambda x: (x[1], x[0])):
perc = (ads / tot_procs) * 100
outcome = "SUCCESS" if not ads else "ACCESS DENIED"
s = templ % (methname, ads, f"{perc:6.1f}%", outcome)
s = templ.format(methname, ads, f"{perc:6.1f}%", outcome)
print_color(s, "red" if ads else None)
tot_perc = round((tot_ads / tot_calls) * 100, 1)
print("-" * 50)
Expand Down
6 changes: 3 additions & 3 deletions scripts/internal/print_api_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@

TIMES = 300
timings = []
templ = "%-25s %10s %10s"
templ = "{:<25} {:>10} {:>10}"


def print_header(what):
s = templ % (what, "NUM CALLS", "SECONDS")
s = templ.format(what, "NUM CALLS", "SECONDS")
print_color(s, color=None, bold=True)
print("-" * len(s))

Expand All @@ -95,7 +95,7 @@ def print_timings():
i = 0
while timings[:]:
title, times, elapsed = timings.pop(0)
s = templ % (title, str(times), f"{elapsed:.5f}")
s = templ.format(title, str(times), f"{elapsed:.5f}")
if i > len(timings) - 5:
print_color(s, color="red")
else:
Expand Down
6 changes: 3 additions & 3 deletions scripts/internal/print_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,15 @@ def main():

tot_files = 0
tot_size = 0
templ = "%-120s %7s %8s %7s"
templ = "{:<120} {:>7} {:>8} {:>7}"
for platf, pkgs in groups.items():
ppn = f"{platf} ({len(pkgs)})"
s = templ % (ppn, "size", "arch", "pyver")
s = templ.format(ppn, "size", "arch", "pyver")
print_color('\n' + s, color=None, bold=True)
for pkg in sorted(pkgs, key=lambda x: x.name):
tot_files += 1
tot_size += pkg.size()
s = templ % (
s = templ.format(
" " + pkg.name,
bytes2human(pkg.size()),
pkg.arch(),
Expand Down
6 changes: 3 additions & 3 deletions scripts/internal/print_downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,18 +111,18 @@ def downloads_by_distro():
# --- print


templ = "| %-30s | %15s |"
templ = "| {:<30} | {:>15} |"


def print_row(left, right):
if isinstance(right, int):
right = f"{right:,}"
print(templ % (left, right))
print(templ.format(left, right))


def print_header(left, right="Downloads"):
print_row(left, right)
s = templ % ("-" * 30, "-" * 15)
s = templ.format("-" * 30, "-" * 15)
print("|:" + s[2:-2] + ":|")


Expand Down
6 changes: 3 additions & 3 deletions scripts/iotop.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def poll(interval):
def refresh_window(procs, disks_read, disks_write):
"""Print results on screen by using curses."""
curses.endwin()
templ = "%-5s %-7s %11s %11s %s"
templ = "{:<5} {:<7} {:>11} {:>11} {}"
win.erase()

disks_tot = "Total DISK READ: {} | Total DISK WRITE: {}".format(
Expand All @@ -124,11 +124,11 @@ def refresh_window(procs, disks_read, disks_write):
)
printl(disks_tot)

header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
header = templ.format("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
printl(header, highlight=True)

for p in procs:
line = templ % (
line = templ.format(
p.pid,
p._username[:7],
bytes2human(p._read_per_sec),
Expand Down
6 changes: 3 additions & 3 deletions scripts/netstat.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@


def main():
templ = "%-5s %-30s %-30s %-13s %-6s %s"
header = templ % (
templ = "{:<5} {:<30} {:<30} {:<13} {:<6} {}"
header = templ.format(
"Proto",
"Local address",
"Remote address",
Expand All @@ -56,7 +56,7 @@ def main():
if c.raddr:
raddr = "{}:{}".format(*c.raddr)
name = proc_names.get(c.pid, '?') or ''
line = templ % (
line = templ.format(
proto_map[(c.family, c.type)],
laddr,
raddr or AD,
Expand Down
12 changes: 6 additions & 6 deletions scripts/nettop.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,27 +95,27 @@ def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
for name in nic_names:
stats_before = pnic_before[name]
stats_after = pnic_after[name]
templ = "%-15s %15s %15s"
templ = "{:<15s} {:>15} {:>15}"
# fmt: off
printl(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
printl(templ % (
printl(templ.format(name, "TOTAL", "PER-SEC"), highlight=True)
printl(templ.format(
"bytes-sent",
bytes2human(stats_after.bytes_sent),
bytes2human(
stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
))
printl(templ % (
printl(templ.format(
"bytes-recv",
bytes2human(stats_after.bytes_recv),
bytes2human(
stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
))
printl(templ % (
printl(templ.format(
"pkts-sent",
stats_after.packets_sent,
stats_after.packets_sent - stats_before.packets_sent,
))
printl(templ % (
printl(templ.format(
"pkts-recv",
stats_after.packets_recv,
stats_after.packets_recv - stats_before.packets_recv,
Expand Down
8 changes: 4 additions & 4 deletions scripts/pmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,20 +47,20 @@ def main():
if len(sys.argv) != 2:
sys.exit('usage: pmap <pid>')
p = psutil.Process(int(sys.argv[1]))
templ = "%-20s %10s %-7s %s"
print(templ % ("Address", "RSS", "Mode", "Mapping"))
templ = "{:<20} {:>10} {:<7} {}"
print(templ.format("Address", "RSS", "Mode", "Mapping"))
total_rss = 0
for m in p.memory_maps(grouped=False):
total_rss += m.rss
line = templ % (
line = templ.format(
m.addr.split('-')[0].zfill(16),
bytes2human(m.rss),
m.perms,
m.path,
)
safe_print(line)
print("-" * 31)
print(templ % ("Total", bytes2human(total_rss), '', ''))
print(templ.format("Total", bytes2human(total_rss), "", ""))
safe_print(f"PID = {p.pid}, name = {p.name()}")


Expand Down
Loading

0 comments on commit 304f08f

Please sign in to comment.