From 2b31b165054b238a54c77da42e1a9797c23ba1f6 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Mon, 23 Dec 2024 15:00:47 +0100 Subject: [PATCH 01/25] add missing rule --- psutil/tests/test_process_all.py | 2 +- psutil/tests/test_testutils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/psutil/tests/test_process_all.py b/psutil/tests/test_process_all.py index 8dd2946c1..6f321407c 100755 --- a/psutil/tests/test_process_all.py +++ b/psutil/tests/test_process_all.py @@ -486,7 +486,7 @@ def tearDown(self): def test_it(self): def is_linux_tid(pid): try: - f = open(f"/proc/{pid}/status", "rb") + f = open(f"/proc/{pid}/status", "rb") # noqa: SIM115 except FileNotFoundError: return False else: diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index e6c3afa85..f886c9048 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -407,7 +407,7 @@ def fun(ls=ls): def test_unclosed_files(self): def fun(): - f = open(__file__) + f = open(__file__) # noqa: SIM115 self.addCleanup(f.close) box.append(f) From c289f68e8664977a69c00f8d67f3b21ade1bfe1e Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:28:05 +0100 Subject: [PATCH 02/25] fix F401 Signed-off-by: Giampaolo Rodola --- psutil/__init__.py | 48 ++++++++++++++--------------- psutil/_common.py | 10 +++--- psutil/_psbsd.py | 6 ++-- psutil/_pslinux.py | 2 +- psutil/tests/__init__.py | 12 ++++---- psutil/tests/test_connections.py | 22 ++++++------- psutil/tests/test_linux.py | 6 ++-- psutil/tests/test_misc.py | 2 +- psutil/tests/test_process.py | 6 ++-- psutil/tests/test_system.py | 6 ++-- psutil/tests/test_testutils.py | 18 +++++------ pyproject.toml | 2 +- scripts/internal/convert_readme.py | 2 +- scripts/internal/print_downloads.py | 2 +- scripts/internal/print_timeline.py | 2 +- scripts/internal/winmake.py | 5 +-- setup.py | 22 ++++++------- 17 files changed, 87 insertions(+), 86 deletions(-) diff --git a/psutil/__init__.py b/psutil/__init__.py index 50b1f2a5c..7ba86eecf 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -51,16 +51,16 @@ from ._common import CONN_SYN_RECV from ._common import CONN_SYN_SENT from ._common import CONN_TIME_WAIT -from ._common import FREEBSD # NOQA +from ._common import FREEBSD from ._common import LINUX from ._common import MACOS -from ._common import NETBSD # NOQA +from ._common import NETBSD from ._common import NIC_DUPLEX_FULL from ._common import NIC_DUPLEX_HALF from ._common import NIC_DUPLEX_UNKNOWN -from ._common import OPENBSD # NOQA +from ._common import OPENBSD from ._common import OSX # deprecated alias -from ._common import POSIX # NOQA +from ._common import POSIX from ._common import POWER_TIME_UNKNOWN from ._common import POWER_TIME_UNLIMITED from ._common import STATUS_DEAD @@ -93,24 +93,24 @@ PROCFS_PATH = "/proc" from . import _pslinux as _psplatform - from ._pslinux import IOPRIO_CLASS_BE # NOQA - from ._pslinux import IOPRIO_CLASS_IDLE # NOQA - from ._pslinux import IOPRIO_CLASS_NONE # NOQA - from ._pslinux import IOPRIO_CLASS_RT # NOQA + from ._pslinux import IOPRIO_CLASS_BE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_IDLE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_NONE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_RT # noqa: F401 elif WINDOWS: from . import _pswindows as _psplatform - from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA - from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA - from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA - from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA - from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA - from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA - from ._pswindows import CONN_DELETE_TCB # NOQA - from ._pswindows import IOPRIO_HIGH # NOQA - from ._pswindows import IOPRIO_LOW # NOQA - from ._pswindows import IOPRIO_NORMAL # NOQA - from ._pswindows import IOPRIO_VERYLOW # NOQA + from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import HIGH_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import IDLE_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import REALTIME_PRIORITY_CLASS # noqa: F401 + from ._pswindows import CONN_DELETE_TCB # noqa: F401 + from ._pswindows import IOPRIO_HIGH # noqa: F401 + from ._pswindows import IOPRIO_LOW # noqa: F401 + from ._pswindows import IOPRIO_NORMAL # noqa: F401 + from ._pswindows import IOPRIO_VERYLOW # noqa: F401 elif MACOS: from . import _psosx as _psplatform @@ -120,8 +120,8 @@ elif SUNOS: from . import _pssunos as _psplatform - from ._pssunos import CONN_BOUND # NOQA - from ._pssunos import CONN_IDLE # NOQA + from ._pssunos import CONN_BOUND # noqa: F401 + from ._pssunos import CONN_IDLE # noqa: F401 # This is public writable API which is read from _pslinux.py and # _pssunos.py via sys.modules. @@ -1201,7 +1201,7 @@ def memory_maps(self, grouped=True): except KeyError: d[path] = nums nt = _psplatform.pmmap_grouped - return [nt(path, *d[path]) for path in d] # NOQA + return [nt(path, *d[path]) for path in d] else: nt = _psplatform.pmmap_ext return [nt(*x) for x in it] @@ -1442,7 +1442,7 @@ def __getattribute__(self, name): def wait(self, timeout=None): if self.__subproc.returncode is not None: return self.__subproc.returncode - ret = super().wait(timeout) # noqa + ret = super().wait(timeout) self.__subproc.returncode = ret return ret @@ -1536,7 +1536,7 @@ def remove(pid): _pmap = pmap -process_iter.cache_clear = lambda: _pmap.clear() # noqa +process_iter.cache_clear = lambda: _pmap.clear() process_iter.cache_clear.__doc__ = "Clear process_iter() internal cache." diff --git a/psutil/_common.py b/psutil/_common.py index a27351f4f..3fca183ab 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -269,7 +269,7 @@ def _infodict(self, attrs): info = collections.OrderedDict() for name in attrs: value = getattr(self, name, None) - if value: # noqa + if value: info[name] = value elif name == "pid" and value == 0: info[name] = value @@ -876,9 +876,9 @@ def print_color( ): # pragma: no cover """Print a colorized version of string.""" if not term_supports_colors(): - print(s, file=file) # NOQA + print(s, file=file) elif POSIX: - print(hilite(s, color, bold), file=file) # NOQA + print(hilite(s, color, bold), file=file) else: import ctypes @@ -906,7 +906,7 @@ def print_color( handle = GetStdHandle(handle_id) SetConsoleTextAttribute(handle, color) try: - print(s, file=file) # NOQA + print(s, file=file) finally: SetConsoleTextAttribute(handle, DEFAULT_COLOR) @@ -925,6 +925,6 @@ def debug(msg): msg = f"ignoring {msg}" else: msg = f"ignoring {msg!r}" - print( # noqa + print( f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr ) diff --git a/psutil/_psbsd.py b/psutil/_psbsd.py index 303b6ad08..4d69a3eb6 100644 --- a/psutil/_psbsd.py +++ b/psutil/_psbsd.py @@ -192,8 +192,8 @@ def virtual_memory(): # #2233), so zabbix seems to be wrong. Htop calculates it # differently, and the used value seem more realistic, so let's # match htop. - # https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 # noqa - # https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 # noqa + # https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 + # https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 used = active + wired avail = total - used else: @@ -202,7 +202,7 @@ def virtual_memory(): # * https://people.freebsd.org/~rse/dist/freebsd-memory # * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt # matches zabbix: - # * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 # noqa + # * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 avail = inactive + cached + free used = active + wired + cached diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 4a539e06e..8d46f9c97 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -934,7 +934,7 @@ def process_unix(file, family, inodes, filter_pid=None): f"error while parsing {file}; malformed line {line!r}" ) raise RuntimeError(msg) # noqa: B904 - if inode in inodes: # noqa + if inode in inodes: # With UNIX sockets we can have a single inode # referencing many file descriptors. pairs = inodes[inode] diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index 9d8378134..f83952e0c 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -707,7 +707,7 @@ def wrapper(*args, **kwargs): for _ in self: try: return fun(*args, **kwargs) - except self.exception as _: # NOQA + except self.exception as _: exc = _ if self.logfun is not None: self.logfun(exc) @@ -1228,7 +1228,7 @@ def _check_mem(self, fun, times, retries, tolerance): return else: if idx == 1: - print() # NOQA + print() self._log(msg) times += increase prev_mem = mem @@ -1365,17 +1365,17 @@ def print_sysinfo(): pinfo.pop('memory_maps', None) info['proc'] = pprint.pformat(pinfo) - print("=" * 70, file=sys.stderr) # NOQA + print("=" * 70, file=sys.stderr) for k, v in info.items(): print("{:<17} {}".format(k + ":", v), file=sys.stderr) # noqa: T201 - print("=" * 70, file=sys.stderr) # NOQA + print("=" * 70, file=sys.stderr) sys.stdout.flush() # if WINDOWS: # os.system("tasklist") # elif shutil.which("ps"): # os.system("ps aux") - # print("=" * 70, file=sys.stderr) # NOQA + # print("=" * 70, file=sys.stderr) sys.stdout.flush() @@ -1621,7 +1621,7 @@ def retry_on_failure(retries=NO_RETRIES): """ def logfun(exc): - print(f"{exc!r}, retrying", file=sys.stderr) # NOQA + print(f"{exc!r}, retrying", file=sys.stderr) return retry( exception=AssertionError, timeout=None, retries=retries, logfun=logfun diff --git a/psutil/tests/test_connections.py b/psutil/tests/test_connections.py index a082f9015..5c89adbc2 100755 --- a/psutil/tests/test_connections.py +++ b/psutil/tests/test_connections.py @@ -184,7 +184,7 @@ def test_unix_tcp(self): testfn = self.get_testfn() with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock: conn = self.check_socket(sock) - assert conn.raddr == "" # noqa + assert conn.raddr == "" assert conn.status == psutil.CONN_NONE @pytest.mark.skipif(not POSIX, reason="POSIX only") @@ -192,7 +192,7 @@ def test_unix_udp(self): testfn = self.get_testfn() with closing(bind_unix_socket(testfn, type=SOCK_STREAM)) as sock: conn = self.check_socket(sock) - assert conn.raddr == "" # noqa + assert conn.raddr == "" assert conn.status == psutil.CONN_NONE @@ -239,8 +239,8 @@ def test_unix(self): assert len(cons) == 2 if LINUX or FREEBSD or SUNOS or OPENBSD: # remote path is never set - assert cons[0].raddr == "" # noqa - assert cons[1].raddr == "" # noqa + assert cons[0].raddr == "" + assert cons[1].raddr == "" # one local address should though assert testfn == (cons[0].laddr or cons[1].laddr) else: @@ -356,14 +356,14 @@ def check_conn(proc, conn, family, type, laddr, raddr, status, kinds): # launch various subprocess instantiating a socket of various # families and types to enrich psutil results tcp4_proc = self.pyrun(tcp4_template) - tcp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa + tcp4_addr = eval(wait_for_file(testfile, delete=True)) udp4_proc = self.pyrun(udp4_template) - udp4_addr = eval(wait_for_file(testfile, delete=True)) # noqa + udp4_addr = eval(wait_for_file(testfile, delete=True)) if supports_ipv6(): tcp6_proc = self.pyrun(tcp6_template) - tcp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa + tcp6_addr = eval(wait_for_file(testfile, delete=True)) udp6_proc = self.pyrun(udp6_template) - udp6_addr = eval(wait_for_file(testfile, delete=True)) # noqa + udp6_addr = eval(wait_for_file(testfile, delete=True)) else: tcp6_proc = None udp6_proc = None @@ -560,7 +560,7 @@ def test_net_connection_constants(self): ints.append(num) strs.append(str_) if SUNOS: - psutil.CONN_IDLE # noqa - psutil.CONN_BOUND # noqa + psutil.CONN_IDLE + psutil.CONN_BOUND if WINDOWS: - psutil.CONN_DELETE_TCB # noqa + psutil.CONN_DELETE_TCB diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 25e4cae11..229b6b125 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -1763,7 +1763,7 @@ def open_mock(name, *args, **kwargs): return orig_open(name, *args, **kwargs) def glob_mock(path): - if path == '/sys/class/hwmon/hwmon*/temp*_*': # noqa + if path == '/sys/class/hwmon/hwmon*/temp*_*': return [] elif path == '/sys/class/hwmon/hwmon*/device/temp*_*': return [] @@ -1780,7 +1780,7 @@ def glob_mock(path): with mock.patch("builtins.open", side_effect=open_mock): with mock.patch('glob.glob', create=True, side_effect=glob_mock): temp = psutil.sensors_temperatures()['name'][0] - assert temp.label == '' # noqa + assert temp.label == '' assert temp.current == 30.0 assert temp.high == 50.0 assert temp.critical == 50.0 @@ -2055,7 +2055,7 @@ def test_exe_mocked(self): ): ret = psutil.Process().exe() assert m.called - assert ret == "" # noqa + assert ret == "" def test_issue_1014(self): # Emulates a case where smaps file does not exist. In this case diff --git a/psutil/tests/test_misc.py b/psutil/tests/test_misc.py index 1c42b6022..848b9284e 100755 --- a/psutil/tests/test_misc.py +++ b/psutil/tests/test_misc.py @@ -100,7 +100,7 @@ def test_error__repr__(self): assert repr(psutil.Error()) == "psutil.Error()" def test_error__str__(self): - assert str(psutil.Error()) == "" # noqa + assert str(psutil.Error()) == "" def test_no_such_process__repr__(self): assert ( diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index 64f71ff15..d4be8bf57 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -1606,7 +1606,7 @@ def __init__(self, *args, **kwargs): def test_(self): try: - meth() # noqa + meth() except psutil.AccessDenied: pass @@ -1664,10 +1664,10 @@ def test_misc(self): ) as proc: proc.name() proc.cpu_times() - proc.stdin # noqa + proc.stdin assert dir(proc) with pytest.raises(AttributeError): - proc.foo # noqa + proc.foo proc.terminate() if POSIX: assert proc.wait(5) == -signal.SIGTERM diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index bcf270545..5fa8bd34a 100755 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -251,8 +251,8 @@ def test_users(self): assert isinstance(user.terminal, (str, type(None))) if user.host is not None: assert isinstance(user.host, (str, type(None))) - user.terminal # noqa - user.host # noqa + user.terminal + user.host assert user.started > 0.0 datetime.datetime.fromtimestamp(user.started) if WINDOWS or OPENBSD: @@ -672,7 +672,7 @@ def check_ntuple(nt): else: # we cannot make any assumption about this, see: # http://goo.gl/p9c43 - disk.device # noqa + disk.device # on modern systems mount points can also be files assert os.path.exists(disk.mountpoint), disk assert disk.fstype, disk diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index f886c9048..83f383df5 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -71,7 +71,7 @@ def test_retry_success(self, sleep): def foo(): while queue: queue.pop() - 1 / 0 # noqa + 1 / 0 return 1 queue = list(range(3)) @@ -85,7 +85,7 @@ def test_retry_failure(self, sleep): def foo(): while queue: queue.pop() - 1 / 0 # noqa + 1 / 0 return 1 queue = list(range(6)) @@ -109,7 +109,7 @@ def test_no_interval_arg(self, sleep): @retry(retries=5, interval=None, logfun=None) def foo(): - 1 / 0 # noqa + 1 / 0 with pytest.raises(ZeroDivisionError): foo() @@ -119,7 +119,7 @@ def foo(): def test_retries_arg(self, sleep): @retry(retries=5, interval=1, logfun=None) def foo(): - 1 / 0 # noqa + 1 / 0 with pytest.raises(ZeroDivisionError): foo() @@ -429,7 +429,7 @@ def fun(): def test_execute_w_exc(self): def fun_1(): - 1 / 0 # noqa + 1 / 0 self.execute_w_exc(ZeroDivisionError, fun_1) with pytest.raises(ZeroDivisionError): @@ -452,7 +452,7 @@ def run_test_class(self, klass): def test_raises(self): with fake_pytest.raises(ZeroDivisionError) as cm: - 1 / 0 # noqa + 1 / 0 assert isinstance(cm.value, ZeroDivisionError) with fake_pytest.raises(ValueError, match="foo") as cm: @@ -484,7 +484,7 @@ def test_skipif(self): class TestCase(unittest.TestCase): @fake_pytest.mark.skipif(True, reason="reason") def foo(self): - assert 1 == 1 # noqa + assert 1 == 1 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() @@ -494,7 +494,7 @@ def foo(self): class TestCase(unittest.TestCase): @fake_pytest.mark.skipif(False, reason="reason") def foo(self): - assert 1 == 1 # noqa + assert 1 == 1 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() @@ -504,7 +504,7 @@ def test_skip(self): class TestCase(unittest.TestCase): def foo(self): fake_pytest.skip("reason") - assert 1 == 0 # noqa + assert 1 == 0 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() diff --git a/pyproject.toml b/pyproject.toml index 5f8ef0691..5f70ac1ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,7 @@ ignore = [ "N806", # Variable X in function should be lowercase. "N818", # Exception name `FooBar` should be named with an Error suffix "PERF", # Perflint - "PGH004", # Use specific rule codes when using `noqa` + # "PGH004", # Use specific rule codes when using `noqa` "PLC0415", # `import` should be at the top-level of a file "PLC2701", # Private name import `x` from external module `y` "PLR0904", # Too many public methods (x > y) diff --git a/scripts/internal/convert_readme.py b/scripts/internal/convert_readme.py index 0c4fade50..9aa75b907 100755 --- a/scripts/internal/convert_readme.py +++ b/scripts/internal/convert_readme.py @@ -36,7 +36,7 @@ `Add your logo `__. -Example usages""" # noqa +Example usages""" def main(): diff --git a/scripts/internal/print_downloads.py b/scripts/internal/print_downloads.py index d8be58a28..610a20182 100755 --- a/scripts/internal/print_downloads.py +++ b/scripts/internal/print_downloads.py @@ -18,7 +18,7 @@ import subprocess import sys -import pypinfo # NOQA +import pypinfo # noqa: F401 from psutil._common import memoize diff --git a/scripts/internal/print_timeline.py b/scripts/internal/print_timeline.py index 6dec932b1..642788914 100755 --- a/scripts/internal/print_timeline.py +++ b/scripts/internal/print_timeline.py @@ -14,7 +14,7 @@ - {date}: `{ver} `__ - `what's new `__ - - `diff `__""" # NOQA + `diff `__""" def sh(cmd): diff --git a/scripts/internal/winmake.py b/scripts/internal/winmake.py index 1692c1253..388238411 100755 --- a/scripts/internal/winmake.py +++ b/scripts/internal/winmake.py @@ -33,7 +33,8 @@ sys.path.insert(0, ROOT_DIR) # so that we can import setup.py -import setup # NOQA +import setup + TEST_DEPS = setup.TEST_DEPS DEV_DEPS = setup.DEV_DEPS @@ -239,7 +240,7 @@ def uninstall(): os.chdir('C:\\') while True: try: - import psutil # NOQA + import psutil # noqa: F401 except ImportError: break else: diff --git a/setup.py b/setup.py index 03077624f..b215bc6eb 100755 --- a/setup.py +++ b/setup.py @@ -58,17 +58,17 @@ # ...so we can import _common.py sys.path.insert(0, os.path.join(HERE, "psutil")) -from _common import AIX # NOQA -from _common import BSD # NOQA -from _common import FREEBSD # NOQA -from _common import LINUX # NOQA -from _common import MACOS # NOQA -from _common import NETBSD # NOQA -from _common import OPENBSD # NOQA -from _common import POSIX # NOQA -from _common import SUNOS # NOQA -from _common import WINDOWS # NOQA -from _common import hilite # NOQA +from _common import AIX +from _common import BSD +from _common import FREEBSD +from _common import LINUX +from _common import MACOS +from _common import NETBSD +from _common import OPENBSD +from _common import POSIX +from _common import SUNOS +from _common import WINDOWS +from _common import hilite PYPY = '__pypy__' in sys.builtin_module_names From 25edf0fb1aab298d91b389948d23e996acaca81e Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:29:00 +0100 Subject: [PATCH 03/25] fix F402 Signed-off-by: Giampaolo Rodola --- scripts/internal/winmake.py | 2 +- setup.py | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/scripts/internal/winmake.py b/scripts/internal/winmake.py index 388238411..b6b9f6d6f 100755 --- a/scripts/internal/winmake.py +++ b/scripts/internal/winmake.py @@ -33,7 +33,7 @@ sys.path.insert(0, ROOT_DIR) # so that we can import setup.py -import setup +import setup # noqa: F401 TEST_DEPS = setup.TEST_DEPS diff --git a/setup.py b/setup.py index b215bc6eb..0014484a8 100755 --- a/setup.py +++ b/setup.py @@ -58,17 +58,17 @@ # ...so we can import _common.py sys.path.insert(0, os.path.join(HERE, "psutil")) -from _common import AIX -from _common import BSD -from _common import FREEBSD -from _common import LINUX -from _common import MACOS -from _common import NETBSD -from _common import OPENBSD -from _common import POSIX -from _common import SUNOS -from _common import WINDOWS -from _common import hilite +from _common import AIX # noqa: E402 +from _common import BSD # noqa: E402 +from _common import FREEBSD # noqa: E402 +from _common import LINUX # noqa: E402 +from _common import MACOS # noqa: E402 +from _common import NETBSD # noqa: E402 +from _common import OPENBSD # noqa: E402 +from _common import POSIX # noqa: E402 +from _common import SUNOS # noqa: E402 +from _common import WINDOWS # noqa: E402 +from _common import hilite # noqa: E402 PYPY = '__pypy__' in sys.builtin_module_names From 4dc370a5568942f703f70749a8bce04823ce24f9 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:30:59 +0100 Subject: [PATCH 04/25] fix T201 Signed-off-by: Giampaolo Rodola --- psutil/_common.py | 6 ++---- psutil/tests/__init__.py | 11 ++++++----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/psutil/_common.py b/psutil/_common.py index 3fca183ab..00f1431a1 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -269,9 +269,7 @@ def _infodict(self, attrs): info = collections.OrderedDict() for name in attrs: value = getattr(self, name, None) - if value: - info[name] = value - elif name == "pid" and value == 0: + if value or name == "pid" and value == 0: info[name] = value return info @@ -925,6 +923,6 @@ def debug(msg): msg = f"ignoring {msg}" else: msg = f"ignoring {msg!r}" - print( + print( # noqa: T201 f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr ) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index f83952e0c..da54398ab 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -1228,7 +1228,7 @@ def _check_mem(self, fun, times, retries, tolerance): return else: if idx == 1: - print() + print() # noqa: T201 self._log(msg) times += increase prev_mem = mem @@ -1363,12 +1363,12 @@ def print_sysinfo(): info['pids'] = len(psutil.pids()) pinfo = psutil.Process().as_dict() pinfo.pop('memory_maps', None) - info['proc'] = pprint.pformat(pinfo) + info['proc'] = pprint.pformat(pinfo) # noqa: T201 - print("=" * 70, file=sys.stderr) + print("=" * 70, file=sys.stderr) # noqa: T201 for k, v in info.items(): print("{:<17} {}".format(k + ":", v), file=sys.stderr) # noqa: T201 - print("=" * 70, file=sys.stderr) + print("=" * 70, file=sys.stderr) # noqa: T201 sys.stdout.flush() # if WINDOWS: @@ -1621,7 +1621,7 @@ def retry_on_failure(retries=NO_RETRIES): """ def logfun(exc): - print(f"{exc!r}, retrying", file=sys.stderr) + print(f"{exc!r}, retrying", file=sys.stderr) # noqa: T201 return retry( exception=AssertionError, timeout=None, retries=retries, logfun=logfun @@ -2025,3 +2025,4 @@ def cleanup_test_procs(): # https://gmpy.dev/blog/2016/how-to-always-execute-exit-functions-in-python if POSIX: signal.signal(signal.SIGTERM, lambda sig, _: sys.exit(sig)) +g)) From 2172a731cac9a641a990ba5348ac6890521c5b9d Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:33:19 +0100 Subject: [PATCH 05/25] another fix Signed-off-by: Giampaolo Rodola --- psutil/tests/__init__.py | 1 - psutil/tests/test_linux.py | 4 +--- scripts/internal/winmake.py | 2 +- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index da54398ab..4fe8dd4e6 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -2025,4 +2025,3 @@ def cleanup_test_procs(): # https://gmpy.dev/blog/2016/how-to-always-execute-exit-functions-in-python if POSIX: signal.signal(signal.SIGTERM, lambda sig, _: sys.exit(sig)) -g)) diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 229b6b125..31e6fa627 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -1763,9 +1763,7 @@ def open_mock(name, *args, **kwargs): return orig_open(name, *args, **kwargs) def glob_mock(path): - if path == '/sys/class/hwmon/hwmon*/temp*_*': - return [] - elif path == '/sys/class/hwmon/hwmon*/device/temp*_*': + if path == '/sys/class/hwmon/hwmon*/temp*_*' or path == '/sys/class/hwmon/hwmon*/device/temp*_*': # noqa: SIM116 return [] elif path == '/sys/class/thermal/thermal_zone*': return ['/sys/class/thermal/thermal_zone0'] diff --git a/scripts/internal/winmake.py b/scripts/internal/winmake.py index b6b9f6d6f..41fb6e746 100755 --- a/scripts/internal/winmake.py +++ b/scripts/internal/winmake.py @@ -33,7 +33,7 @@ sys.path.insert(0, ROOT_DIR) # so that we can import setup.py -import setup # noqa: F401 +import setup # noqa: E402 TEST_DEPS = setup.TEST_DEPS From 89ce5b12cff1b73e1954da7f70f26a48c38d52c3 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:35:00 +0100 Subject: [PATCH 06/25] more fixes Signed-off-by: Giampaolo Rodola --- psutil/__init__.py | 2 +- psutil/_pslinux.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/psutil/__init__.py b/psutil/__init__.py index 7ba86eecf..8aece5213 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -1536,7 +1536,7 @@ def remove(pid): _pmap = pmap -process_iter.cache_clear = lambda: _pmap.clear() +process_iter.cache_clear = lambda: _pmap.clear() # noqa: PLW0108 process_iter.cache_clear.__doc__ = "Clear process_iter() internal cache." diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 8d46f9c97..b2a70769b 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -934,7 +934,7 @@ def process_unix(file, family, inodes, filter_pid=None): f"error while parsing {file}; malformed line {line!r}" ) raise RuntimeError(msg) # noqa: B904 - if inode in inodes: + if inode in inodes: # noqa: SIM108, SIM401 # With UNIX sockets we can have a single inode # referencing many file descriptors. pairs = inodes[inode] From 1d82d563af722dd17704defe76c0c6b4e01c0473 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:36:50 +0100 Subject: [PATCH 07/25] more fixes Signed-off-by: Giampaolo Rodola --- psutil/tests/test_linux.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/psutil/tests/test_linux.py b/psutil/tests/test_linux.py index 31e6fa627..3672bc959 100755 --- a/psutil/tests/test_linux.py +++ b/psutil/tests/test_linux.py @@ -1763,7 +1763,10 @@ def open_mock(name, *args, **kwargs): return orig_open(name, *args, **kwargs) def glob_mock(path): - if path == '/sys/class/hwmon/hwmon*/temp*_*' or path == '/sys/class/hwmon/hwmon*/device/temp*_*': # noqa: SIM116 + if path in { + '/sys/class/hwmon/hwmon*/temp*_*', + '/sys/class/hwmon/hwmon*/device/temp*_*', + }: return [] elif path == '/sys/class/thermal/thermal_zone*': return ['/sys/class/thermal/thermal_zone0'] From ea134486efb4e5b03e018283bc6876f5e907f67d Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:38:35 +0100 Subject: [PATCH 08/25] fix PLR0133 Signed-off-by: Giampaolo Rodola --- psutil/tests/test_testutils.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index 83f383df5..cfa2901ea 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -484,7 +484,7 @@ def test_skipif(self): class TestCase(unittest.TestCase): @fake_pytest.mark.skipif(True, reason="reason") def foo(self): - assert 1 == 1 + assert 1 == 1 # noqa: PLR0133 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() @@ -494,7 +494,7 @@ def foo(self): class TestCase(unittest.TestCase): @fake_pytest.mark.skipif(False, reason="reason") def foo(self): - assert 1 == 1 + assert 1 == 1 # noqa: PLR0133 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() @@ -504,7 +504,7 @@ def test_skip(self): class TestCase(unittest.TestCase): def foo(self): fake_pytest.skip("reason") - assert 1 == 0 + assert 1 == 0 # noqa: PLR0133 result = self.run_test_class(TestCase("foo")) assert result.wasSuccessful() From f134ac6c6616d47bdc20104058f0bba61fa5739d Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:39:10 +0100 Subject: [PATCH 09/25] more fixes Signed-off-by: Giampaolo Rodola --- psutil/__init__.py | 2 +- psutil/_psbsd.py | 2 +- psutil/tests/__init__.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/psutil/__init__.py b/psutil/__init__.py index 8aece5213..bc17aabf1 100644 --- a/psutil/__init__.py +++ b/psutil/__init__.py @@ -1619,7 +1619,7 @@ def check_gone(proc, timeout): check_gone(proc, timeout) else: check_gone(proc, max_timeout) - alive = alive - gone # noqa PLR6104 + alive = alive - gone # noqa: PLR6104 if alive: # Last attempt over processes survived so far. diff --git a/psutil/_psbsd.py b/psutil/_psbsd.py index 4d69a3eb6..13bd926fa 100644 --- a/psutil/_psbsd.py +++ b/psutil/_psbsd.py @@ -10,7 +10,7 @@ import os from collections import defaultdict from collections import namedtuple -from xml.etree import ElementTree # noqa ICN001 +from xml.etree import ElementTree # noqa: ICN001 from . import _common from . import _psposix diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index 4fe8dd4e6..275dcdad4 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -890,7 +890,7 @@ class fake_pytest: """ @staticmethod - def main(*args, **kw): # noqa ARG004 + def main(*args, **kw): # noqa: ARG004 """Mimics pytest.main(). It has the same effect as running `python3 -m unittest -v` from the project root directory. """ From 84471894bc0f7d75c51608ef3083d20df40e5e91 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:40:36 +0100 Subject: [PATCH 10/25] fix line too long Signed-off-by: Giampaolo Rodola --- scripts/internal/print_timeline.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/internal/print_timeline.py b/scripts/internal/print_timeline.py index 642788914..940724129 100755 --- a/scripts/internal/print_timeline.py +++ b/scripts/internal/print_timeline.py @@ -14,7 +14,7 @@ - {date}: `{ver} `__ - `what's new `__ - - `diff `__""" + `diff `__""" # noqa: E501 def sh(cmd): From 4861da1ae4374dac71ee03cab6360afa501109e7 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:42:28 +0100 Subject: [PATCH 11/25] fix B018 Signed-off-by: Giampaolo Rodola --- psutil/tests/test_connections.py | 6 +++--- psutil/tests/test_process.py | 4 ++-- psutil/tests/test_system.py | 6 +++--- psutil/tests/test_testutils.py | 12 ++++++------ 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/psutil/tests/test_connections.py b/psutil/tests/test_connections.py index 5c89adbc2..5ddeb855f 100755 --- a/psutil/tests/test_connections.py +++ b/psutil/tests/test_connections.py @@ -560,7 +560,7 @@ def test_net_connection_constants(self): ints.append(num) strs.append(str_) if SUNOS: - psutil.CONN_IDLE - psutil.CONN_BOUND + psutil.CONN_IDLE # noqa: B018 + psutil.CONN_BOUND # noqa: B018 if WINDOWS: - psutil.CONN_DELETE_TCB + psutil.CONN_DELETE_TCB # noqa: B018 diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index d4be8bf57..ceb434a7d 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -1664,10 +1664,10 @@ def test_misc(self): ) as proc: proc.name() proc.cpu_times() - proc.stdin + proc.stdin # noqa: B018 assert dir(proc) with pytest.raises(AttributeError): - proc.foo + proc.foo # noqa: B018 proc.terminate() if POSIX: assert proc.wait(5) == -signal.SIGTERM diff --git a/psutil/tests/test_system.py b/psutil/tests/test_system.py index 5fa8bd34a..f2eb40548 100755 --- a/psutil/tests/test_system.py +++ b/psutil/tests/test_system.py @@ -251,8 +251,8 @@ def test_users(self): assert isinstance(user.terminal, (str, type(None))) if user.host is not None: assert isinstance(user.host, (str, type(None))) - user.terminal - user.host + user.terminal # noqa: B018 + user.host # noqa: B018 assert user.started > 0.0 datetime.datetime.fromtimestamp(user.started) if WINDOWS or OPENBSD: @@ -672,7 +672,7 @@ def check_ntuple(nt): else: # we cannot make any assumption about this, see: # http://goo.gl/p9c43 - disk.device + disk.device # noqa: B018 # on modern systems mount points can also be files assert os.path.exists(disk.mountpoint), disk assert disk.fstype, disk diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index cfa2901ea..91594f2a1 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -71,7 +71,7 @@ def test_retry_success(self, sleep): def foo(): while queue: queue.pop() - 1 / 0 + 1 / 0 # noqa: B018 return 1 queue = list(range(3)) @@ -85,7 +85,7 @@ def test_retry_failure(self, sleep): def foo(): while queue: queue.pop() - 1 / 0 + 1 / 0 # noqa: B018 return 1 queue = list(range(6)) @@ -109,7 +109,7 @@ def test_no_interval_arg(self, sleep): @retry(retries=5, interval=None, logfun=None) def foo(): - 1 / 0 + 1 / 0 # noqa: B018 with pytest.raises(ZeroDivisionError): foo() @@ -119,7 +119,7 @@ def foo(): def test_retries_arg(self, sleep): @retry(retries=5, interval=1, logfun=None) def foo(): - 1 / 0 + 1 / 0 # noqa: B018 with pytest.raises(ZeroDivisionError): foo() @@ -429,7 +429,7 @@ def fun(): def test_execute_w_exc(self): def fun_1(): - 1 / 0 + 1 / 0 # noqa: B018 self.execute_w_exc(ZeroDivisionError, fun_1) with pytest.raises(ZeroDivisionError): @@ -452,7 +452,7 @@ def run_test_class(self, klass): def test_raises(self): with fake_pytest.raises(ZeroDivisionError) as cm: - 1 / 0 + 1 / 0 # noqa: B018 assert isinstance(cm.value, ZeroDivisionError) with fake_pytest.raises(ValueError, match="foo") as cm: From 7dedb4935e11ab891709cd35421e2af5a8891df9 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:45:20 +0100 Subject: [PATCH 12/25] fix rule Signed-off-by: Giampaolo Rodola --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 5f70ac1ed..6118cd496 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,8 +58,8 @@ ignore = [ "N806", # Variable X in function should be lowercase. "N818", # Exception name `FooBar` should be named with an Error suffix "PERF", # Perflint - # "PGH004", # Use specific rule codes when using `noqa` "PLC0415", # `import` should be at the top-level of a file + "PLC1901", # PLC1901 `x == ""` can be simplified to `not x` as an empty string is falsey "PLC2701", # Private name import `x` from external module `y` "PLR0904", # Too many public methods (x > y) "PLR0911", # Too many return statements (8 > 6) From c2da28a8652e78e2fd010419d19f0a750efb84ca Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:50:22 +0100 Subject: [PATCH 13/25] remove LimitedUserTestCase, added 16 years ago (useless) --- psutil/tests/test_process.py | 57 ------------------------------------ 1 file changed, 57 deletions(-) diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index ceb434a7d..d14eabfe0 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -21,7 +21,6 @@ import sys import textwrap import time -import types from unittest import mock import psutil @@ -1579,62 +1578,6 @@ def test_weird_environ(self): assert sproc.returncode == 0 -# =================================================================== -# --- Limited user tests -# =================================================================== - - -if POSIX and os.getuid() == 0: - - class LimitedUserTestCase(TestProcess): - """Repeat the previous tests by using a limited user. - Executed only on UNIX and only if the user who run the test script - is root. - """ - - # the uid/gid the test suite runs under - if hasattr(os, 'getuid'): - PROCESS_UID = os.getuid() - PROCESS_GID = os.getgid() - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - # re-define all existent test methods in order to - # ignore AccessDenied exceptions - for attr in [x for x in dir(self) if x.startswith('test')]: - meth = getattr(self, attr) - - def test_(self): - try: - meth() - except psutil.AccessDenied: - pass - - setattr(self, attr, types.MethodType(test_, self)) - - def setUp(self): - super().setUp() - os.setegid(1000) - os.seteuid(1000) - - def tearDown(self): - os.setegid(self.PROCESS_UID) - os.seteuid(self.PROCESS_GID) - super().tearDown() - - def test_nice(self): - try: - psutil.Process().nice(-1) - except psutil.AccessDenied: - pass - else: - raise self.fail("exception not raised") - - @pytest.mark.skipif(True, reason="causes problem as root") - def test_zombie_process(self): - pass - - # =================================================================== # --- psutil.Popen tests # =================================================================== From 898d4950683c742169ea999bc804575acbbb2150 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:57:25 +0100 Subject: [PATCH 14/25] add new RUF* rules Signed-off-by: Giampaolo Rodola --- pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 6118cd496..ecbdf86a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -80,7 +80,10 @@ ignore = [ "PYI", # flake8-pyi (python types stuff) "Q000", # Single quotes found but double quotes preferred "RET", # flake8-return - "RUF", # Ruff-specific rules + "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` + "RUF022", # `__all__` is not sorted + # "RUF", # Ruff-specific rules + "RUF028", # This suppression comment is invalid "S", # flake8-bandit "SIM102", # Use a single `if` statement instead of nested `if` statements "SIM105", # Use `contextlib.suppress(OSError)` instead of `try`-`except`-`pass` From 00d6d4d6dbd18b7d5bc426100b227702462a94d9 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 15:58:59 +0100 Subject: [PATCH 15/25] add new RUF* rules Signed-off-by: Giampaolo Rodola --- psutil/_pswindows.py | 8 ++++---- psutil/tests/__init__.py | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/psutil/_pswindows.py b/psutil/_pswindows.py index a28180264..a02a36c06 100644 --- a/psutil/_pswindows.py +++ b/psutil/_pswindows.py @@ -983,10 +983,10 @@ def open_files(self): # Convert the first part in the corresponding drive letter # (e.g. "C:\") by using Windows's QueryDosDevice() raw_file_names = cext.proc_open_files(self.pid) - for _file in raw_file_names: - _file = convert_dos_path(_file) - if isfile_strict(_file): - ntuple = _common.popenfile(_file, -1) + for file in rawfile_names: + file = convert_dos_path(file) + if isfile_strict(file): + ntuple = _common.popenfile(file, -1) ret.add(ntuple) return list(ret) diff --git a/psutil/tests/__init__.py b/psutil/tests/__init__.py index 275dcdad4..3817f8b12 100644 --- a/psutil/tests/__init__.py +++ b/psutil/tests/__init__.py @@ -714,7 +714,7 @@ def wrapper(*args, **kwargs): self.sleep() continue - raise exc # noqa: PLE0704 + raise exc # This way the user of the decorated function can change config # parameters. @@ -1363,7 +1363,7 @@ def print_sysinfo(): info['pids'] = len(psutil.pids()) pinfo = psutil.Process().as_dict() pinfo.pop('memory_maps', None) - info['proc'] = pprint.pformat(pinfo) # noqa: T201 + info['proc'] = pprint.pformat(pinfo) print("=" * 70, file=sys.stderr) # noqa: T201 for k, v in info.items(): From fb4a261971de957405d539427154262abfd7e116 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:01:18 +0100 Subject: [PATCH 16/25] add new RUF* rules Signed-off-by: Giampaolo Rodola --- psutil/_pswindows.py | 2 +- pyproject.toml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/psutil/_pswindows.py b/psutil/_pswindows.py index a02a36c06..69820ba41 100644 --- a/psutil/_pswindows.py +++ b/psutil/_pswindows.py @@ -983,7 +983,7 @@ def open_files(self): # Convert the first part in the corresponding drive letter # (e.g. "C:\") by using Windows's QueryDosDevice() raw_file_names = cext.proc_open_files(self.pid) - for file in rawfile_names: + for file in raw_file_names: file = convert_dos_path(file) if isfile_strict(file): ntuple = _common.popenfile(file, -1) diff --git a/pyproject.toml b/pyproject.toml index ecbdf86a3..056e2bd7a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,6 +84,7 @@ ignore = [ "RUF022", # `__all__` is not sorted # "RUF", # Ruff-specific rules "RUF028", # This suppression comment is invalid + "RUF031", # [*] Avoid parentheses for tuples in subscripts "S", # flake8-bandit "SIM102", # Use a single `if` statement instead of nested `if` statements "SIM105", # Use `contextlib.suppress(OSError)` instead of `try`-`except`-`pass` From 938b32241cbf23971608151156de752df6fb2d0e Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:05:55 +0100 Subject: [PATCH 17/25] add new RUF* rules Signed-off-by: Giampaolo Rodola --- psutil/_common.py | 2 +- psutil/_pslinux.py | 2 +- psutil/tests/test_osx.py | 2 +- psutil/tests/test_process.py | 2 +- psutil/tests/test_testutils.py | 4 ++-- psutil/tests/test_windows.py | 2 +- pyproject.toml | 2 +- scripts/internal/check_broken_links.py | 4 ++-- scripts/pidof.py | 6 ++---- 9 files changed, 12 insertions(+), 14 deletions(-) diff --git a/psutil/_common.py b/psutil/_common.py index 00f1431a1..0c385fa6a 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -269,7 +269,7 @@ def _infodict(self, attrs): info = collections.OrderedDict() for name in attrs: value = getattr(self, name, None) - if value or name == "pid" and value == 0: + if value or (name == "pid" and value == 0): info[name] = value return info diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index b2a70769b..5a0ab2d2e 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -1327,7 +1327,7 @@ def sensors_temperatures(): basenames2 = glob.glob( '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*' ) - repl = re.compile('/sys/devices/platform/coretemp.*/hwmon/') + repl = re.compile(r"/sys/devices/platform/coretemp.*/hwmon/") for name in basenames2: altname = repl.sub('/sys/class/hwmon/', name) if altname not in basenames: diff --git a/psutil/tests/test_osx.py b/psutil/tests/test_osx.py index 682012ecf..62895ccdd 100755 --- a/psutil/tests/test_osx.py +++ b/psutil/tests/test_osx.py @@ -185,7 +185,7 @@ def test_net_if_stats(self): def test_sensors_battery(self): out = sh("pmset -g batt") percent = re.search(r"(\d+)%", out).group(1) - drawing_from = re.search("Now drawing from '([^']+)'", out).group(1) + drawing_from = re.search(r"Now drawing from '([^']+)'", out).group(1) power_plugged = drawing_from == "AC Power" psutil_result = psutil.sensors_battery() assert psutil_result.power_plugged == power_plugged diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index d14eabfe0..1a04a0018 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -624,7 +624,7 @@ def test_memory_full_info(self): for name in mem._fields: value = getattr(mem, name) assert value >= 0 - if name == 'vms' and OSX or LINUX: + if (name == "vms" and OSX) or LINUX: continue assert value <= total if LINUX or WINDOWS or MACOS: diff --git a/psutil/tests/test_testutils.py b/psutil/tests/test_testutils.py index 91594f2a1..85f20c14e 100755 --- a/psutil/tests/test_testutils.py +++ b/psutil/tests/test_testutils.py @@ -564,12 +564,12 @@ def test_process_namespace(self): p = psutil.Process() ns = process_namespace(p) ns.test() - fun = [x for x in ns.iter(ns.getters) if x[1] == 'ppid'][0][0] + fun = next(x for x in ns.iter(ns.getters) if x[1] == 'ppid')[0] assert fun() == p.ppid() def test_system_namespace(self): ns = system_namespace() - fun = [x for x in ns.iter(ns.getters) if x[1] == 'net_if_addrs'][0][0] + fun = next(x for x in ns.iter(ns.getters) if x[1] == 'net_if_addrs')[0] assert fun() == psutil.net_if_addrs() diff --git a/psutil/tests/test_windows.py b/psutil/tests/test_windows.py index 667f1d686..9f54cf534 100755 --- a/psutil/tests/test_windows.py +++ b/psutil/tests/test_windows.py @@ -429,7 +429,7 @@ def test_username(self): assert psutil.Process().username() == name def test_cmdline(self): - sys_value = re.sub('[ ]+', ' ', win32api.GetCommandLine()).strip() + sys_value = re.sub(r"[ ]+", " ", win32api.GetCommandLine()).strip() psutil_value = ' '.join(psutil.Process().cmdline()) if sys_value[0] == '"' != psutil_value[0]: # The PyWin32 command line may retain quotes around argv[0] if they diff --git a/pyproject.toml b/pyproject.toml index 056e2bd7a..bba7341ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -80,9 +80,9 @@ ignore = [ "PYI", # flake8-pyi (python types stuff) "Q000", # Single quotes found but double quotes preferred "RET", # flake8-return + "RUF005", # Consider iterable unpacking instead of concatenation "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` "RUF022", # `__all__` is not sorted - # "RUF", # Ruff-specific rules "RUF028", # This suppression comment is invalid "RUF031", # [*] Avoid parentheses for tuples in subscripts "S", # flake8-bandit diff --git a/scripts/internal/check_broken_links.py b/scripts/internal/check_broken_links.py index 2a51381d3..2c6852b9a 100755 --- a/scripts/internal/check_broken_links.py +++ b/scripts/internal/check_broken_links.py @@ -122,7 +122,7 @@ def parse_py(fname): subidx = i + 1 while True: nextline = lines[subidx].strip() - if re.match('^# .+', nextline): + if re.match(r"^# .+", nextline): url += nextline[1:].strip() else: break @@ -143,7 +143,7 @@ def parse_c(fname): subidx = i + 1 while True: nextline = lines[subidx].strip() - if re.match('^// .+', nextline): + if re.match(r"^// .+", nextline): url += nextline[2:].strip() else: break diff --git a/scripts/pidof.py b/scripts/pidof.py index 7c3b93d8a..c5af54c85 100755 --- a/scripts/pidof.py +++ b/scripts/pidof.py @@ -21,10 +21,8 @@ def pidof(pgname): pids = [] for proc in psutil.process_iter(['name', 'cmdline']): # search for matches in the process name and cmdline - if ( - proc.info['name'] == pgname - or proc.info['cmdline'] - and proc.info['cmdline'][0] == pgname + if proc.info["name"] == pgname or ( + proc.info["cmdline"] and proc.info["cmdline"][0] == pgname ): pids.append(str(proc.pid)) return pids From ef8e66c82cabcd91c6ce0f5b2b26b99409f40d60 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:14:55 +0100 Subject: [PATCH 18/25] add new RUF* rules Signed-off-by: Giampaolo Rodola --- psutil/_pslinux.py | 2 +- psutil/tests/test_process.py | 2 +- pyproject.toml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/psutil/_pslinux.py b/psutil/_pslinux.py index 5a0ab2d2e..165125fdf 100644 --- a/psutil/_pslinux.py +++ b/psutil/_pslinux.py @@ -1480,7 +1480,7 @@ def multi_bcat(*paths): # Get the first available battery. Usually this is "BAT0", except # some rare exceptions: # https://github.com/giampaolo/psutil/issues/1238 - root = os.path.join(POWER_SUPPLY_PATH, sorted(bats)[0]) + root = os.path.join(POWER_SUPPLY_PATH, min(bats)) # Base metrics. energy_now = multi_bcat(root + "/energy_now", root + "/charge_now") diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index 1a04a0018..45a86c3b7 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -1209,7 +1209,7 @@ def test_children_duplicates(self): except psutil.Error: pass # this is the one, now let's make sure there are no duplicates - pid = sorted(table.items(), key=lambda x: x[1])[-1][0] + pid = max(table.items(), key=lambda x: x[1])[0] if LINUX and pid == 0: raise pytest.skip("PID 0") p = psutil.Process(pid) diff --git a/pyproject.toml b/pyproject.toml index bba7341ff..6424b8797 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ ignore = [ "FURB116", # [*] Replace `hex` call with `f"{start:x}"` "FURB118", # [*] Use `operator.add` instead of defining a lambda "FURB140", # [*] Use `itertools.starmap` instead of the generator - "FURB192", # [*] Prefer `min` over `sorted()` to compute the minimum value in a sequence + # "FURB192", # [*] Prefer `min` over `sorted()` to compute the minimum value in a sequence "INP", # flake8-no-pep420 "N801", # Class name `async_chat` should use CapWords convention (ASYNCORE COMPAT) "N802", # Function name X should be lowercase. From c2e2e9067de7a7b79be849e059c801733036f254 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:20:29 +0100 Subject: [PATCH 19/25] progress --- pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 6424b8797..49749e311 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,6 @@ ignore = [ "FURB116", # [*] Replace `hex` call with `f"{start:x}"` "FURB118", # [*] Use `operator.add` instead of defining a lambda "FURB140", # [*] Use `itertools.starmap` instead of the generator - # "FURB192", # [*] Prefer `min` over `sorted()` to compute the minimum value in a sequence "INP", # flake8-no-pep420 "N801", # Class name `async_chat` should use CapWords convention (ASYNCORE COMPAT) "N802", # Function name X should be lowercase. From 28676e0d78ae71b0e6165c6d25c18dd3b13e32d1 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:21:47 +0100 Subject: [PATCH 20/25] new ruff rule --- pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 49749e311..a91e6ad40 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,6 @@ ignore = [ "N818", # Exception name `FooBar` should be named with an Error suffix "PERF", # Perflint "PLC0415", # `import` should be at the top-level of a file - "PLC1901", # PLC1901 `x == ""` can be simplified to `not x` as an empty string is falsey "PLC2701", # Private name import `x` from external module `y` "PLR0904", # Too many public methods (x > y) "PLR0911", # Too many return statements (8 > 6) @@ -102,9 +101,10 @@ ignore = [ # T201 == print() # T203 == pprint() # TRY003 == raise-vanilla-args -# "B904", # Use `raise from` to specify exception cause +# B904 == Use `raise from` to specify exception cause +# PLC1901 == `x == ""` can be simplified to `not x` as an empty string is falsey ".github/workflows/*" = ["B904", "EM101", "EM102", "EM103", "T201", "T203"] -"psutil/tests/*" = ["B904", "EM101", "EM102", "EM103", "TRY003"] +"psutil/tests/*" = ["B904", "EM101", "EM102", "EM103", "PLC1901", "TRY003"] "scripts/*" = ["B904", "EM101", "EM102", "EM103", "T201", "T203"] "scripts/internal/*" = ["B904", "EM101", "EM102", "EM103", "T201", "T203", "TRY003"] "setup.py" = [ From 5388ca5d2eb75b62c7df851b386da51bc6a34cbf Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Fri, 27 Dec 2024 16:24:42 +0100 Subject: [PATCH 21/25] update ruff rules --- pyproject.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index a91e6ad40..f6eb772d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,9 @@ ignore = [ "PTH", # flake8-use-pathlib "PYI", # flake8-pyi (python types stuff) "Q000", # Single quotes found but double quotes preferred - "RET", # flake8-return + "RET503", # Missing explicit `return` at the end of function able to return non-`None` value + "RET504", # Unnecessary assignment to `result` before `return` statement + "RET505", # [*] Unnecessary `else` after `return` statement "RUF005", # Consider iterable unpacking instead of concatenation "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` "RUF022", # `__all__` is not sorted From 78abfff96b2ad028d75b7b60da5db5c60965748d Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sat, 28 Dec 2024 10:55:58 +0100 Subject: [PATCH 22/25] fix test on bsd --- psutil/tests/test_process_all.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/psutil/tests/test_process_all.py b/psutil/tests/test_process_all.py index 6f321407c..cb7264d73 100755 --- a/psutil/tests/test_process_all.py +++ b/psutil/tests/test_process_all.py @@ -410,11 +410,14 @@ def memory_maps(self, ret, info): for fname in nt._fields: value = getattr(nt, fname) if fname == 'path': - if not value.startswith(("[", "anon_inode:")): - assert os.path.isabs(nt.path), nt.path - # commented as on Linux we might get - # '/foo/bar (deleted)' - # assert os.path.exists(nt.path), nt.path + if value.startswith(("[", "anon_inode:")): # linux + continue + if BSD and value == "pvclock": # seen on FreeBSD + continue + assert os.path.isabs(nt.path), nt.path + # commented as on Linux we might get + # '/foo/bar (deleted)' + # assert os.path.exists(nt.path), nt.path elif fname == 'addr': assert value, repr(value) elif fname == 'perms': From 7e513f0f444c998f45845b610b58886867e17317 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sat, 28 Dec 2024 11:19:46 +0100 Subject: [PATCH 23/25] fix test on bsd --- psutil/tests/test_process.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index 45a86c3b7..60831bd60 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -644,7 +644,8 @@ def test_memory_maps(self): if not nt.path.startswith('['): if QEMU_USER and "/bin/qemu-" in nt.path: continue - assert os.path.isabs(nt.path), nt.path + if not (BSD and nt.path == "pvclock"): + assert os.path.isabs(nt.path), nt.path if POSIX: try: assert os.path.exists(nt.path) or os.path.islink( From 4b1e7c9500fdf2150be5b0d202f788eeb2489f71 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sat, 28 Dec 2024 12:31:44 +0100 Subject: [PATCH 24/25] fix test on bsd --- psutil/tests/test_process.py | 60 +++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/psutil/tests/test_process.py b/psutil/tests/test_process.py index 60831bd60..1d81d498f 100755 --- a/psutil/tests/test_process.py +++ b/psutil/tests/test_process.py @@ -641,34 +641,38 @@ def test_memory_maps(self): ext_maps = p.memory_maps(grouped=False) for nt in maps: - if not nt.path.startswith('['): - if QEMU_USER and "/bin/qemu-" in nt.path: - continue - if not (BSD and nt.path == "pvclock"): - assert os.path.isabs(nt.path), nt.path - if POSIX: - try: - assert os.path.exists(nt.path) or os.path.islink( - nt.path - ), nt.path - except AssertionError: - if not LINUX: - raise - # https://github.com/giampaolo/psutil/issues/759 - with open_text('/proc/self/smaps') as f: - data = f.read() - if f"{nt.path} (deleted)" not in data: - raise - elif '64' not in os.path.basename(nt.path): - # XXX - On Windows we have this strange behavior with - # 64 bit dlls: they are visible via explorer but cannot - # be accessed via os.stat() (wtf?). - try: - st = os.stat(nt.path) - except FileNotFoundError: - pass - else: - assert stat.S_ISREG(st.st_mode), nt.path + if nt.path.startswith('['): + continue + if BSD and nt.path == "pvclock": + continue + if QEMU_USER and "/bin/qemu-" in nt.path: + continue + assert os.path.isabs(nt.path), nt.path + + if POSIX: + try: + assert os.path.exists(nt.path) or os.path.islink( + nt.path + ), nt.path + except AssertionError: + if not LINUX: + raise + # https://github.com/giampaolo/psutil/issues/759 + with open_text('/proc/self/smaps') as f: + data = f.read() + if f"{nt.path} (deleted)" not in data: + raise + elif '64' not in os.path.basename(nt.path): + # XXX - On Windows we have this strange behavior with + # 64 bit dlls: they are visible via explorer but cannot + # be accessed via os.stat() (wtf?). + try: + st = os.stat(nt.path) + except FileNotFoundError: + pass + else: + assert stat.S_ISREG(st.st_mode), nt.path + for nt in ext_maps: for fname in nt._fields: value = getattr(nt, fname) From f840c4b314b27e1d2fc9ec9fd2d747f877681437 Mon Sep 17 00:00:00 2001 From: Giampaolo Rodola Date: Sat, 28 Dec 2024 13:10:00 +0100 Subject: [PATCH 25/25] adjust double open() --- .github/workflows/issues.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/issues.py b/.github/workflows/issues.py index 1cdc4d996..21c720ca5 100755 --- a/.github/workflows/issues.py +++ b/.github/workflows/issues.py @@ -159,7 +159,7 @@ def get_repo(): @functools.lru_cache() def _get_event_data(): - with open(open(os.environ["GITHUB_EVENT_PATH"])) as f: + with open(os.environ["GITHUB_EVENT_PATH"]) as f: ret = json.load(f) pp(ret) return ret