From 304f08f8b270b59138bad09fdb20f01160870bfd Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 20 Dec 2024 23:23:34 +0100 Subject: [PATCH] Use str.format() instead of % (#2485) --- psutil/_pslinux.py | 4 +-- psutil/tests/__init__.py | 2 +- psutil/tests/test_linux.py | 2 +- psutil/tests/test_system.py | 9 +++--- scripts/disk_usage.py | 10 ++++-- scripts/free.py | 10 +++--- scripts/internal/print_access_denied.py | 6 ++-- scripts/internal/print_api_speed.py | 6 ++-- scripts/internal/print_dist.py | 6 ++-- scripts/internal/print_downloads.py | 6 ++-- scripts/iotop.py | 6 ++-- scripts/netstat.py | 6 ++-- scripts/nettop.py | 12 ++++---- scripts/pmap.py | 8 ++--- scripts/procinfo.py | 41 +++++++++++++------------ scripts/procsmem.py | 6 ++-- scripts/ps.py | 8 ++--- scripts/sensors.py | 5 +-- scripts/top.py | 6 ++-- setup.py | 2 +- 20 files changed, 85 insertions(+), 76 deletions(-) diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index ad1e1eff2..81ec88bda 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -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: @@ -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]) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index 10f4cd877..54f468f51 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -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() diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 945e0f535..741a15237 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -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)) diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index b66ff5fd9..723aaa337 100755 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -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): @@ -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): @@ -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): diff --git a/scripts/disk_usage.py b/scripts/disk_usage.py index c75c4f61d..be391e28a 100755 --- a/scripts/disk_usage.py +++ b/scripts/disk_usage.py @@ -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: @@ -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), diff --git a/scripts/free.py b/scripts/free.py index 332507284..c891b6fc9 100755 --- a/scripts/free.py +++ b/scripts/free.py @@ -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), @@ -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), diff --git a/scripts/internal/print_access_denied.py b/scripts/internal/print_access_denied.py index 4df2e63b4..b92e9bfc2 100755 --- a/scripts/internal/print_access_denied.py +++ b/scripts/internal/print_access_denied.py @@ -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) diff --git a/scripts/internal/print_api_speed.py b/scripts/internal/print_api_speed.py index 5c155f4d3..e421d83d8 100755 --- a/scripts/internal/print_api_speed.py +++ b/scripts/internal/print_api_speed.py @@ -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)) @@ -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: diff --git a/scripts/internal/print_dist.py b/scripts/internal/print_dist.py index decd12c49..3ff399e22 100755 --- a/scripts/internal/print_dist.py +++ b/scripts/internal/print_dist.py @@ -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(), diff --git a/scripts/internal/print_downloads.py b/scripts/internal/print_downloads.py index 70afd4b83..d8be58a28 100755 --- a/scripts/internal/print_downloads.py +++ b/scripts/internal/print_downloads.py @@ -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] + ":|") diff --git a/scripts/iotop.py b/scripts/iotop.py index f56f828e5..93f46d157 100755 --- a/scripts/iotop.py +++ b/scripts/iotop.py @@ -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( @@ -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), diff --git a/scripts/netstat.py b/scripts/netstat.py index 912bed9df..56924e6ae 100755 --- a/scripts/netstat.py +++ b/scripts/netstat.py @@ -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", @@ -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, diff --git a/scripts/nettop.py b/scripts/nettop.py index cda16bf07..222771edc 100755 --- a/scripts/nettop.py +++ b/scripts/nettop.py @@ -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, diff --git a/scripts/pmap.py b/scripts/pmap.py index ae633a41b..54d53bebd 100755 --- a/scripts/pmap.py +++ b/scripts/pmap.py @@ -47,12 +47,12 @@ def main(): if len(sys.argv) != 2: sys.exit('usage: pmap ') 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, @@ -60,7 +60,7 @@ def main(): ) 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()}") diff --git a/scripts/procinfo.py b/scripts/procinfo.py index 5feb49bd3..4a328d506 100755 --- a/scripts/procinfo.py +++ b/scripts/procinfo.py @@ -221,13 +221,13 @@ def run(pid, verbose=False): if 'num_ctx_switches' in pinfo: print_("ctx-switches", str_ntuple(pinfo['num_ctx_switches'])) if pinfo['children']: - template = "%-6s %s" - print_("children", template % ("PID", "NAME")) + template = "{:<6} {}" + print_("children", template.format("PID", "NAME")) for child in pinfo['children']: try: - print_('', template % (child.pid, child.name())) + print_("", template.format(child.pid, child.name())) except psutil.AccessDenied: - print_('', template % (child.pid, "")) + print_("", template.format(child.pid, "")) except psutil.NoSuchProcess: pass @@ -242,10 +242,10 @@ def run(pid, verbose=False): print_('open-files', '') if pinfo['net_connections']: - template = '%-5s %-25s %-25s %s' + template = "{:<5} {:<25} {:<25} {}" print_( 'connections', - template % ('PROTO', 'LOCAL ADDR', 'REMOTE ADDR', 'STATUS'), + template.format("PROTO", "LOCAL ADDR", "REMOTE ADDR", "STATUS"), ) for conn in pinfo['net_connections']: if conn.type == socket.SOCK_STREAM: @@ -259,7 +259,7 @@ def run(pid, verbose=False): rip, rport = '*', '*' else: rip, rport = conn.raddr - line = template % ( + line = template.format( type, f"{lip}:{lport}", f"{rip}:{rport}", @@ -270,13 +270,13 @@ def run(pid, verbose=False): print_('connections', '') if pinfo['threads'] and len(pinfo['threads']) > 1: - template = "%-5s %12s %12s" - print_('threads', template % ("TID", "USER", "SYSTEM")) + template = "{:<5} {:>12} {:>12}" + print_("threads", template.format("TID", "USER", "SYSTEM")) for i, thread in enumerate(pinfo['threads']): if not verbose and i >= NON_VERBOSE_ITERATIONS: print_("", "[...]") break - print_('', template % thread) + print_("", template.format(*thread)) print_('', f"total={len(pinfo['threads'])}") else: print_('threads', '') @@ -292,8 +292,8 @@ def run(pid, verbose=False): else: resources.append((res_name, soft, hard)) if resources: - template = "%-12s %15s %15s" - print_("res-limits", template % ("RLIMIT", "SOFT", "HARD")) + template = "{:<12} {:>15} {:>15}" + print_("res-limits", template.format("RLIMIT", "SOFT", "HARD")) for res_name, soft, hard in resources: if soft == psutil.RLIM_INFINITY: soft = "infinity" @@ -301,28 +301,29 @@ def run(pid, verbose=False): hard = "infinity" print_( '', - template - % (RLIMITS_MAP.get(res_name, res_name), soft, hard), + template.format( + RLIMITS_MAP.get(res_name, res_name), soft, hard + ), ) if hasattr(proc, "environ") and pinfo['environ']: - template = "%-25s %s" - print_("environ", template % ("NAME", "VALUE")) + template = "{:<25} {}" + print_("environ", template.format("NAME", "VALUE")) for i, k in enumerate(sorted(pinfo['environ'])): if not verbose and i >= NON_VERBOSE_ITERATIONS: print_("", "[...]") break - print_("", template % (k, pinfo['environ'][k])) + print_("", template.format(k, pinfo["environ"][k])) if pinfo.get('memory_maps', None): - template = "%-8s %s" - print_("mem-maps", template % ("RSS", "PATH")) + template = "{:<8} {}" + print_("mem-maps", template.format("RSS", "PATH")) maps = sorted(pinfo['memory_maps'], key=lambda x: x.rss, reverse=True) for i, region in enumerate(maps): if not verbose and i >= NON_VERBOSE_ITERATIONS: print_("", "[...]") break - print_("", template % (bytes2human(region.rss), region.path)) + print_("", template.format(bytes2human(region.rss), region.path)) def main(): diff --git a/scripts/procsmem.py b/scripts/procsmem.py index 17eee8fb0..bf58f203d 100755 --- a/scripts/procsmem.py +++ b/scripts/procsmem.py @@ -80,12 +80,12 @@ def main(): procs.append(p) procs.sort(key=lambda p: p._uss) - templ = "%-7s %-7s %7s %7s %7s %7s %7s" - print(templ % ("PID", "User", "USS", "PSS", "Swap", "RSS", "Cmdline")) + templ = "{:<7} {:<7} {:>7} {:>7} {:>7} {:>7} {:>7}" + print(templ.format("PID", "User", "USS", "PSS", "Swap", "RSS", "Cmdline")) print("=" * 78) for p in procs[:86]: cmd = " ".join(p._info["cmdline"])[:50] if p._info["cmdline"] else "" - line = templ % ( + line = templ.format( p.pid, p._info["username"][:7] if p._info["username"] else "", convert_bytes(p._uss), diff --git a/scripts/ps.py b/scripts/ps.py index 8478bbd1a..585eca2f4 100755 --- a/scripts/ps.py +++ b/scripts/ps.py @@ -42,11 +42,11 @@ def main(): today_day = datetime.date.today() # fmt: off - templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s" + templ = "{:<10} {:>5} {:>5} {:>7} {:>7} {:>5} {:>6} {:>6} {:>6} {}" attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times', 'create_time', 'memory_info', 'status', 'nice', 'username'] - print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", - "STATUS", "START", "TIME", "CMDLINE")) + print(templ.format("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", + "STATUS", "START", "TIME", "CMDLINE")) # fmt: on for p in psutil.process_iter(attrs, ad_value=None): if p.info['create_time']: @@ -97,7 +97,7 @@ def main(): cmdline = p.info['name'] status = p.info['status'][:5] if p.info['status'] else '' - line = templ % ( + line = templ.format( user, p.info['pid'], memp, diff --git a/scripts/sensors.py b/scripts/sensors.py index 05aec894a..ba7a9edca 100755 --- a/scripts/sensors.py +++ b/scripts/sensors.py @@ -82,8 +82,9 @@ def main(): print(f" charge: {round(battery.percent, 2)}%") if battery.power_plugged: print( - " status: %s" - % ("charging" if battery.percent < 100 else "fully charged") + " status: {}".format( + "charging" if battery.percent < 100 else "fully charged" + ) ) print(" plugged in: yes") else: diff --git a/scripts/top.py b/scripts/top.py index 46fca7553..f772bdf00 100755 --- a/scripts/top.py +++ b/scripts/top.py @@ -182,9 +182,9 @@ def get_dashes(perc): def refresh_window(procs, procs_status): """Print results on screen by using curses.""" curses.endwin() - templ = "%-6s %-8s %4s %6s %6s %5s %5s %9s %2s" + templ = "{:<6} {:<8} {:>4} {:>6} {:>6} {:>5} {:>5} {:>9} {:>2}" win.erase() - header = templ % ( + header = templ.format( "PID", "USER", "NI", @@ -217,7 +217,7 @@ def refresh_window(procs, procs_status): if p.dict['cpu_percent'] is None: p.dict['cpu_percent'] = '' username = p.dict['username'][:8] if p.dict['username'] else '' - line = templ % ( + line = templ.format( p.pid, username, p.dict['nice'], diff --git a/setup.py b/setup.py index 6b68d511a..864c25461 100755 --- a/setup.py +++ b/setup.py @@ -247,7 +247,7 @@ def unix_can_compile(c_code): def get_winver(): maj, min = sys.getwindowsversion()[0:2] - return '0x0%s' % ((maj * 100) + min) + return "0x0{}".format((maj * 100) + min) if sys.getwindowsversion()[0] < 6: msg = "this Windows version is too old (< Windows Vista); "