Skip to content

Commit

Permalink
use str.format() instead of % / percent format
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Dec 20, 2024
1 parent 573c95d commit 28bc732
Show file tree
Hide file tree
Showing 16 changed files with 57 additions and 54 deletions.
21 changes: 9 additions & 12 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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()]),
Expand Down Expand Up @@ -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)),
)
Expand Down
10 changes: 5 additions & 5 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)
Expand Down
14 changes: 8 additions & 6 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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),
Expand Down
12 changes: 7 additions & 5 deletions psutil/tests/test_process_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()}"
Expand Down
5 changes: 3 additions & 2 deletions psutil/tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
16 changes: 10 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 3 additions & 6 deletions scripts/ifconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions scripts/internal/print_access_denied.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
)


Expand Down
2 changes: 1 addition & 1 deletion scripts/internal/print_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion scripts/iotop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
Expand Down
4 changes: 2 additions & 2 deletions scripts/netstat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)],
Expand Down
2 changes: 1 addition & 1 deletion scripts/procinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
4 changes: 2 additions & 2 deletions scripts/top.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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],
Expand Down
2 changes: 1 addition & 1 deletion scripts/who.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion scripts/winservices.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down

0 comments on commit 28bc732

Please sign in to comment.