diff --git a/psutil/__init__.py b/psutil/__init__.py index 160c813d8..eaed048b3 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -227,19 +227,16 @@ msg = f"version conflict: {_psplatform.cext.__file__!r} C extension " msg += "module was built for another version of psutil" if hasattr(_psplatform.cext, 'version'): - msg += " (%s instead of %s)" % ( - '.'.join([x for x in str(_psplatform.cext.version)]), - __version__, - ) + v = ".".join([x for x in str(_psplatform.cext.version)]) + msg += f" ({v} instead of {__version__})" else: msg += f" (different than {__version__})" - msg += "; you may try to 'pip uninstall psutil', manually remove %s" % ( - getattr( - _psplatform.cext, - "__file__", - "the existing psutil install directory", - ) + what = getattr( + _psplatform.cext, + "__file__", + "the existing psutil install directory", ) + msg += f"; you may try to 'pip uninstall psutil', manually remove {what}" msg += " or clean the virtual env somehow, then reinstall" raise ImportError(msg) @@ -417,7 +414,7 @@ def __str__(self): if self._create_time is not None: info['started'] = _pprint_secs(self._create_time) - return "%s.%s(%s)" % ( + return "{}.{}({})".format( self.__class__.__module__, self.__class__.__name__, ", ".join([f"{k}={v!r}" for k, v in info.items()]), @@ -559,7 +556,7 @@ def as_dict(self, attrs=None, ad_value=None): attrs = set(attrs) invalid_names = attrs - valid_names if invalid_names: - msg = "invalid attr name%s %s" % ( + msg = "invalid attr name{} {}".format( "s" if len(invalid_names) > 1 else "", ", ".join(map(repr, invalid_names)), ) diff --git a/psutil/_common.py b/psutil/_common.py index 1e8bb7959..e7c6ba3dd 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -279,8 +279,8 @@ def __str__(self): # invoked on `raise Error` info = self._infodict(("pid", "ppid", "name")) if info: - details = "(%s)" % ", ".join( - ["%s=%r" % (k, v) for k, v in info.items()] + details = "({})".format( + ", ".join([f"{k}={v!r}" for k, v in info.items()]) ) else: details = None @@ -611,9 +611,9 @@ def deprecated_method(replacement): """ def outer(fun): - msg = "%s() is deprecated and will be removed; use %s() instead" % ( - fun.__name__, - replacement, + msg = ( + f"{fun.__name__}() is deprecated and will be removed; use" + f" {replacement}() instead" ) if fun.__doc__ is None: fun.__doc__ = msg diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 531503d55..ad1e1eff2 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -461,7 +461,7 @@ def virtual_memory(): # Warn about missing metrics which are set to 0. if missing_fields: - msg = "%s memory stats couldn't be determined and %s set to 0" % ( + msg = "{} memory stats couldn't be determined and {} set to 0".format( ", ".join(missing_fields), "was" if len(missing_fields) == 1 else "were", ) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index c852ead0a..10f4cd877 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -248,7 +248,9 @@ def attempt(exe): exe = ( attempt(sys.executable) or attempt(os.path.realpath(sys.executable)) - or attempt(shutil.which("python%s.%s" % sys.version_info[:2])) + or attempt( + shutil.which("python{}.{}".format(*sys.version_info[:2])) + ) or attempt(psutil.Process().exe()) ) if not exe: @@ -1212,7 +1214,7 @@ def _check_mem(self, fun, times, retries, tolerance): increase = times for idx in range(1, retries + 1): mem = self._call_ntimes(fun, times) - msg = "Run #%s: extra-mem=%s, per-call=%s, calls=%s" % ( + msg = "Run #{}: extra-mem={}, per-call={}, calls={}".format( idx, bytes2human(mem), bytes2human(mem / times), @@ -1343,17 +1345,17 @@ def print_sysinfo(): # metrics info['cpus'] = psutil.cpu_count() - info['loadavg'] = "%.1f%%, %.1f%%, %.1f%%" % ( - tuple([x / psutil.cpu_count() * 100 for x in psutil.getloadavg()]) + info['loadavg'] = "{:.1f}%, {:.1f}%, {:.1f}%".format( + *tuple([x / psutil.cpu_count() * 100 for x in psutil.getloadavg()]) ) mem = psutil.virtual_memory() - info['memory'] = "%s%%, used=%s, total=%s" % ( + info['memory'] = "{}%%, used={}, total={}".format( int(mem.percent), bytes2human(mem.used), bytes2human(mem.total), ) swap = psutil.swap_memory() - info['swap'] = "%s%%, used=%s, total=%s" % ( + info['swap'] = "{}%%, used={}, total={}".format( int(swap.percent), bytes2human(swap.used), bytes2human(swap.total), diff --git a/psutil/tests/test_process_all.py b/psutil/tests/test_process_all.py index 24229979c..8dd2946c1 100755 --- a/psutil/tests/test_process_all.py +++ b/psutil/tests/test_process_all.py @@ -135,11 +135,13 @@ def test_all(self): meth(value, info) except Exception: # noqa: BLE001 s = '\n' + '=' * 70 + '\n' - s += "FAIL: name=test_%s, pid=%s, ret=%s\ninfo=%s\n" % ( - name, - info['pid'], - repr(value), - info, + s += ( + "FAIL: name=test_{}, pid={}, ret={}\ninfo={}\n".format( + name, + info['pid'], + repr(value), + info, + ) ) s += '-' * 70 s += f"\n{traceback.format_exc()}" diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index 62d49bf61..391dbbfda 100755 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -513,8 +513,9 @@ def _test_cpu_percent(self, percent, last_ret, new_ret): assert percent <= 100.0 * psutil.cpu_count() except AssertionError as err: raise AssertionError( - "\n%s\nlast=%s\nnew=%s" - % (err, pprint.pformat(last_ret), pprint.pformat(new_ret)) + "\n{}\nlast={}\nnew={}".format( + err, pprint.pformat(last_ret), pprint.pformat(new_ret) + ) ) def test_cpu_percent(self): diff --git a/pyproject.toml b/pyproject.toml index d6e87a5bd..fa5cd07a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -89,17 +89,21 @@ ignore = [ "TD", # all TODOs, XXXs, etc. "TRY300", # Consider moving this statement to an `else` block "TRY301", # Abstract `raise` to an inner function - "UP031", # [*] Use format specifiers instead of percent format + "UP032", # [*] Use f-string instead of `format` call ] [tool.ruff.lint.per-file-ignores] # EM101 == raw-string-in-exception -# T201 == print(), T203 == pprint() +# EM102 == f-string-in-exception +# EM103 == dot-format-in-exception +# T201 == print() +# T203 == pprint() # TRY003 == raise-vanilla-args -".github/workflows/*" = ["EM102", "T201", "T203"] -"psutil/tests/*" = ["EM101", "EM102", "TRY003"] -"scripts/*" = ["EM102", "T201", "T203"] -"scripts/internal/*" = ["EM101", "EM102", "T201", "T203", "TRY003"] +# UP031 == Use format specifiers instead of percent format +".github/workflows/*" = ["EM101", "EM102", "EM103", "T201", "T203"] +"psutil/tests/*" = ["EM101", "EM102", "EM103", "TRY003"] +"scripts/*" = ["EM101", "EM102", "EM103", "T201", "T203", "UP031"] +"scripts/internal/*" = ["EM101", "EM102", "EM103", "T201", "T203", "TRY003", "UP031"] "setup.py" = [ "B904", # Use ` raise from` to specify exception cause (PYTHON2.7 COMPAT) "C4", # flake8-comprehensions (PYTHON2.7 COMPAT) diff --git a/scripts/ifconfig.py b/scripts/ifconfig.py index dfc5f5ae4..93a14b952 100755 --- a/scripts/ifconfig.py +++ b/scripts/ifconfig.py @@ -71,8 +71,7 @@ def main(): st = stats[nic] print(" stats : ", end='') print( - "speed=%sMB, duplex=%s, mtu=%s, up=%s" - % ( + "speed={}MB, duplex={}, mtu={}, up={}".format( st.speed, duplex_map[st.duplex], st.mtu, @@ -83,8 +82,7 @@ def main(): io = io_counters[nic] print(" incoming : ", end='') print( - "bytes=%s, pkts=%s, errs=%s, drops=%s" - % ( + "bytes={}, pkts={}, errs={}, drops={}".format( bytes2human(io.bytes_recv), io.packets_recv, io.errin, @@ -93,8 +91,7 @@ def main(): ) print(" outgoing : ", end='') print( - "bytes=%s, pkts=%s, errs=%s, drops=%s" - % ( + "bytes={}, pkts={}, errs={}, drops={}".format( bytes2human(io.bytes_sent), io.packets_sent, io.errout, diff --git a/scripts/internal/print_access_denied.py b/scripts/internal/print_access_denied.py index dbf96f2d8..4df2e63b4 100755 --- a/scripts/internal/print_access_denied.py +++ b/scripts/internal/print_access_denied.py @@ -83,8 +83,8 @@ def main(): tot_perc = round((tot_ads / tot_calls) * 100, 1) print("-" * 50) print( - "Totals: access-denied=%s (%s%%), calls=%s, processes=%s, elapsed=%ss" - % (tot_ads, tot_perc, tot_calls, tot_procs, round(elapsed, 2)) + "Totals: access-denied={} ({}%%), calls={}, processes={}, elapsed={}s" + .format(tot_ads, tot_perc, tot_calls, tot_procs, round(elapsed, 2)) ) diff --git a/scripts/internal/print_dist.py b/scripts/internal/print_dist.py index 5e2a6e598..decd12c49 100755 --- a/scripts/internal/print_dist.py +++ b/scripts/internal/print_dist.py @@ -20,7 +20,7 @@ def __init__(self, path): self._name = os.path.basename(path) def __repr__(self): - return "<%s(name=%s, plat=%s, arch=%s, pyver=%s)>" % ( + return "<{}(name={}, plat={}, arch={}, pyver={})>".format( self.__class__.__name__, self.name, self.platform(), diff --git a/scripts/iotop.py b/scripts/iotop.py index 2d92f4e2d..f56f828e5 100755 --- a/scripts/iotop.py +++ b/scripts/iotop.py @@ -118,7 +118,7 @@ def refresh_window(procs, disks_read, disks_write): templ = "%-5s %-7s %11s %11s %s" win.erase() - disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" % ( + disks_tot = "Total DISK READ: {} | Total DISK WRITE: {}".format( bytes2human(disks_read), bytes2human(disks_write), ) diff --git a/scripts/netstat.py b/scripts/netstat.py index b58900937..912bed9df 100755 --- a/scripts/netstat.py +++ b/scripts/netstat.py @@ -51,10 +51,10 @@ def main(): for p in psutil.process_iter(['pid', 'name']): proc_names[p.info['pid']] = p.info['name'] for c in psutil.net_connections(kind='inet'): - laddr = "%s:%s" % (c.laddr) + laddr = "{}:{}".format(*c.laddr) raddr = "" if c.raddr: - raddr = "%s:%s" % (c.raddr) + raddr = "{}:{}".format(*c.raddr) name = proc_names.get(c.pid, '?') or '' line = templ % ( proto_map[(c.family, c.type)], diff --git a/scripts/procinfo.py b/scripts/procinfo.py index 963dd77da..afdda11b7 100755 --- a/scripts/procinfo.py +++ b/scripts/procinfo.py @@ -172,7 +172,7 @@ def run(pid, verbose=False): print_('started', started) cpu_tot_time = datetime.timedelta(seconds=sum(pinfo['cpu_times'])) - cpu_tot_time = "%s:%s.%s" % ( + cpu_tot_time = "{}:{}.{}".format( cpu_tot_time.seconds // 60 % 60, str(cpu_tot_time.seconds % 60).zfill(2), str(cpu_tot_time.microseconds)[:2], diff --git a/scripts/top.py b/scripts/top.py index 03f235ec3..993f47780 100755 --- a/scripts/top.py +++ b/scripts/top.py @@ -168,7 +168,7 @@ def get_dashes(perc): psutil.boot_time() ) av1, av2, av3 = psutil.getloadavg() - line = " Load average: %.2f %.2f %.2f Uptime: %s" % ( + line = " Load average: {:.2f} {:.2f} {:.2f} Uptime: {}".format( av1, av2, av3, @@ -201,7 +201,7 @@ def refresh_window(procs, procs_status): # is expressed as: "mm:ss.ms" if p.dict['cpu_times'] is not None: ctime = datetime.timedelta(seconds=sum(p.dict['cpu_times'])) - ctime = "%s:%s.%s" % ( + ctime = "{}:{}.{}".format( ctime.seconds // 60 % 60, str(ctime.seconds % 60).zfill(2), str(ctime.microseconds)[:2], diff --git a/scripts/who.py b/scripts/who.py index 64a948107..094c4fd1c 100755 --- a/scripts/who.py +++ b/scripts/who.py @@ -25,7 +25,7 @@ def main(): user.name, user.terminal or '-', datetime.fromtimestamp(user.started).strftime("%Y-%m-%d %H:%M"), - "(%s)" % user.host if user.host else "", + f"({user.host or ''})", proc_name, ) print(line) diff --git a/scripts/winservices.py b/scripts/winservices.py index 6ff240c1d..7df589459 100755 --- a/scripts/winservices.py +++ b/scripts/winservices.py @@ -44,7 +44,7 @@ def main(): for service in psutil.win_service_iter(): info = service.as_dict() print(f"{info['name']!r} ({info['display_name']!r})") - s = "status: %s, start: %s, username: %s, pid: %s" % ( + s = "status: {}, start: {}, username: {}, pid: {}".format( info['status'], info['start_type'], info['username'],