diff --git a/psutil/__init__.py b/psutil/__init__.py index d4d08df8c..160c813d8 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -420,7 +420,7 @@ def __str__(self): return "%s.%s(%s)" % ( self.__class__.__module__, self.__class__.__name__, - ", ".join(["%s=%r" % (k, v) for k, v in info.items()]), + ", ".join([f"{k}={v!r}" for k, v in info.items()]), ) __repr__ = __str__ @@ -1176,7 +1176,7 @@ def memory_percent(self, memtype="rss"): # we should never get here msg = ( "can't calculate process memory percent because total physical" - " system memory is not positive (%r)" % (total_phymem) + f" system memory is not positive ({total_phymem!r})" ) raise ValueError(msg) return (value / float(total_phymem)) * 100 diff --git a/psutil/_common.py b/psutil/_common.py index c0b84b923..1e8bb7959 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -863,9 +863,8 @@ def hilite(s, color=None, bold=False): # pragma: no cover try: color = colors[color] except KeyError: - raise ValueError( - "invalid color %r; choose between %s" % (list(colors.keys())) - ) + msg = f"invalid color {color!r}; choose amongst {list(colors.keys())}" + raise ValueError(msg) attr.append(color) if bold: attr.append('1') diff --git a/psutil/_psbsd.py b/psutil/_psbsd.py index aa033bb36..6f6eeb35f 100644 --- a/psutil/_psbsd.py +++ b/psutil/_psbsd.py @@ -964,9 +964,10 @@ def rlimit(self, resource, limits=None): return cext.proc_getrlimit(self.pid, resource) else: if len(limits) != 2: - raise ValueError( - "second argument must be a (soft, hard) tuple, got %s" - % repr(limits) + msg = ( + "second argument must be a (soft, hard) tuple, got" + f" {limits!r}" ) + raise ValueError(msg) soft, hard = limits return cext.proc_setrlimit(self.pid, resource, soft, hard) diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 1202c0cbd..531503d55 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -324,9 +324,8 @@ def calculate_avail_vmem(mems): slab_reclaimable = mems[b'SReclaimable:'] except KeyError as err: debug( - "%s is missing from /proc/meminfo; using an approximation for " - "calculating available memory" - % err.args[0] + f"{err.args[0]} is missing from /proc/meminfo; using an" + " approximation for calculating available memory" ) return fallback try: @@ -1149,11 +1148,11 @@ def read_sysfs(): elif os.path.exists('/sys/block'): gen = read_sysfs() else: - raise NotImplementedError( - "%s/diskstats nor /sys/block filesystem are available on this " - "system" - % get_procfs_path() + msg = ( + f"{get_procfs_path()}/diskstats nor /sys/block are available on" + " this system" ) + raise NotImplementedError(msg) retdict = {} for entry in gen: @@ -1856,10 +1855,11 @@ def io_counters(self): fields[b'wchar'], # write chars ) except KeyError as err: - raise ValueError( - "%r field was not found in %s; found fields are %r" - % (err.args[0], fname, fields) + msg = ( + f"{err.args[0]!r} field was not found in {fname}; found" + f" fields are {fields!r}" ) + raise ValueError(msg) @wrap_exceptions def cpu_times(self): @@ -2068,11 +2068,13 @@ def num_ctx_switches( data = self._read_status_file() ctxsw = _ctxsw_re.findall(data) if not ctxsw: - raise NotImplementedError( - "'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'" - "lines were not found in %s/%s/status; the kernel is " - "probably older than 2.6.23" % (self._procfs_path, self.pid) + msg = ( + "'voluntary_ctxt_switches' and" + " 'nonvoluntary_ctxt_switches'lines were not found in" + f" {self._procfs_path}/{self.pid}/status; the kernel is" + " probably older than 2.6.23" ) + raise NotImplementedError(msg) else: return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1])) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index 455936847..c852ead0a 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -289,7 +289,7 @@ def __init__(self): def __repr__(self): name = self.__class__.__name__ - return '<%s running=%s at %#x>' % (name, self._running, id(self)) + return f"<{name} running={self._running} at {id(self):#x}>" def __enter__(self): self.start() @@ -391,16 +391,16 @@ def spawn_children_pair(): tfile = None testfn = get_testfn(dir=os.getcwd()) try: - s = textwrap.dedent("""\ + s = textwrap.dedent(f"""\ import subprocess, os, sys, time s = "import os, time;" - s += "f = open('%s', 'w');" + s += "f = open('{os.path.basename(testfn)}', 'w');" s += "f.write(str(os.getpid()));" s += "f.close();" s += "[time.sleep(0.1) for x in range(100 * 6)];" - p = subprocess.Popen([r'%s', '-c', s]) + p = subprocess.Popen([r'{PYTHON_EXE}', '-c', s]) p.wait() - """ % (os.path.basename(testfn), PYTHON_EXE)) + """) # On Windows if we create a subprocess with CREATE_NO_WINDOW flag # set (which is the default) a "conhost.exe" extra process will be # spawned as a child. We don't want that. @@ -1179,10 +1179,11 @@ def _check_fds(self, fun): after = self._get_num_fds() diff = after - before if diff < 0: - raise self.fail( - "negative diff %r (gc probably collected a " - "resource from a previous test)" % diff + msg = ( + f"negative diff {diff!r} (gc probably collected a" + " resource from a previous test)" ) + raise self.fail(msg) if diff > 0: type_ = "fd" if POSIX else "handle" if diff > 1: @@ -1526,9 +1527,9 @@ def test_class_coverage(cls, test_class, ls): for fun_name, _, _ in ls: meth_name = 'test_' + fun_name if not hasattr(test_class, meth_name): - msg = "%r class should define a '%s' method" % ( - test_class.__class__.__name__, - meth_name, + msg = ( + f"{test_class.__class__.__name__!r} class should define a" + f" {meth_name!r} method" ) raise AttributeError(msg) @@ -1657,8 +1658,8 @@ def wrapper(*args, **kwargs): if not only_if: raise msg = ( - "%r was skipped because it raised NotImplementedError" - % fun.__name__ + f"{fun.__name__!r} was skipped because it raised" + " NotImplementedError" ) raise pytest.skip(msg) diff --git a/psutil/tests/test_aix.py b/psutil/tests/test_aix.py index 2b0f849be..10934c12d 100755 --- a/psutil/tests/test_aix.py +++ b/psutil/tests/test_aix.py @@ -31,7 +31,7 @@ def test_virtual_memory(self): "available", "mmode", ]: - re_pattern += r"(?P<%s>\S+)\s+" % (field,) + re_pattern += rf"(?P<{field}>\S+)\s+" matchobj = re.search(re_pattern, out) assert matchobj is not None @@ -104,7 +104,7 @@ def test_cpu_stats(self): "S5rd", "sysc", ]: - re_pattern += r"(?P<%s>\S+)\s+" % (field,) + re_pattern += rf"(?P<{field}>\S+)\s+" matchobj = re.search(re_pattern, out) assert matchobj is not None diff --git a/psutil/tests/test_connections.py b/psutil/tests/test_connections.py index 47f69fed5..a082f9015 100755 --- a/psutil/tests/test_connections.py +++ b/psutil/tests/test_connections.py @@ -522,14 +522,14 @@ def test_multi_sockets_procs(self): for _ in range(times): fname = self.get_testfn() fnames.append(fname) - src = textwrap.dedent("""\ + src = textwrap.dedent(f"""\ import time, os from psutil.tests import create_sockets with create_sockets(): - with open(r'%s', 'w') as f: + with open(r'{fname}', 'w') as f: f.write("hello") [time.sleep(0.1) for x in range(100)] - """ % fname) + """) sproc = self.pyrun(src) pids.append(sproc.pid) diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 5719868ec..4c36d27d8 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -146,7 +146,7 @@ def free_swap(): nt = collections.namedtuple('free', 'total used free') return nt(int(total), int(used), int(free)) raise ValueError( - "can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines) + f"can't find 'Swap' in 'free' output:\n{'\n'.join(lines)}" ) @@ -167,9 +167,7 @@ def free_physmem(): 'free', 'total used free shared output' ) return nt(total, used, free, shared, out) - raise ValueError( - "can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines) - ) + raise ValueError(f"can't find 'Mem' in 'free' output:\n{'\n'.join(lines)}") def vmstat(stat): diff --git a/psutil/tests/test_misc.py b/psutil/tests/test_misc.py index fdfc72696..9d24bb32c 100755 --- a/psutil/tests/test_misc.py +++ b/psutil/tests/test_misc.py @@ -941,8 +941,8 @@ def test_coverage(self): if 'test_' + os.path.splitext(name)[0] not in meths: # self.assert_stdout(name) raise self.fail( - 'no test defined for %r script' - % os.path.join(SCRIPTS_DIR, name) + "no test defined for" + f" {os.path.join(SCRIPTS_DIR, name)!r} script" ) @pytest.mark.skipif(not POSIX, reason="POSIX only") diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index db1dcda71..45129ddca 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -1072,8 +1072,8 @@ def test_open_files(self): # another process cmdline = ( - "import time; f = open(r'%s', 'r'); [time.sleep(0.1) for x in" - " range(100)];" % testfn + f"import time; f = open(r'{testfn}', 'r'); [time.sleep(0.1) for x" + " in range(100)];" ) p = self.spawn_psproc([PYTHON_EXE, "-c", cmdline]) diff --git a/scripts/internal/bench_oneshot.py b/scripts/internal/bench_oneshot.py index 090237539..299f9cea6 100755 --- a/scripts/internal/bench_oneshot.py +++ b/scripts/internal/bench_oneshot.py @@ -126,8 +126,9 @@ def call_oneshot(funs): def main(): print( - "%s methods involved on platform %r (%s iterations, psutil %s):" - % (len(names), sys.platform, ITERATIONS, psutil.__version__) + f"{len(names)} methods involved on platform" + f" {sys.platform!r} ({ITERATIONS} iterations, psutil" + f" {psutil.__version__}):" ) for name in sorted(names): print(" " + name) diff --git a/scripts/internal/bench_oneshot_2.py b/scripts/internal/bench_oneshot_2.py index 41c9cbb89..1076dffc8 100755 --- a/scripts/internal/bench_oneshot_2.py +++ b/scripts/internal/bench_oneshot_2.py @@ -37,8 +37,8 @@ def main(): args = runner.parse_args() if not args.worker: print( - "%s methods involved on platform %r (psutil %s):" - % (len(names), sys.platform, psutil.__version__) + f"{len(names)} methods involved on platform" + f" {sys.platform!r} (psutil {psutil.__version__}):" ) for name in sorted(names): print(" " + name) diff --git a/scripts/internal/winmake.py b/scripts/internal/winmake.py index 2267ce410..5413b827b 100755 --- a/scripts/internal/winmake.py +++ b/scripts/internal/winmake.py @@ -467,7 +467,7 @@ def get_python(path): '312-64', ) for v in vers: - pypath = r'C:\\python%s\python.exe' % v + pypath = rf"C:\\python{v}\python.exe" if path in pypath and os.path.isfile(pypath): return pypath