Skip to content

Commit

Permalink
add more ruff rules
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Jan 4, 2024
1 parent 03d5aa9 commit 63e579f
Show file tree
Hide file tree
Showing 23 changed files with 114 additions and 84 deletions.
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ include LICENSE
include MANIFEST.in
include Makefile
include README.rst
include SECURITY.md
include docs/.readthedocs.yaml
include docs/DEVGUIDE.rst
include docs/DEVNOTES
Expand Down
10 changes: 10 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Security Policy

If you have discovered a security vulnerability in this project, please report
it privately. **Do not disclose it as a public issue**. This gives me time to
fix the issue before public exposure, reducing the chance that an exploit will
be used before a patch is released.

To report a security vulnerability use the [Tidelift security
contact](https://tidelift.com/security). Tidelift will coordinate the fix and
the disclosure of the reported problem.
7 changes: 3 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,8 @@ def get_version():
for num in ret.split('.'):
assert num.isdigit(), ret
return ret
else:
msg = "couldn't find version string"
raise ValueError(msg)
msg = "couldn't find version string"
raise ValueError(msg)


VERSION = get_version()
Expand Down Expand Up @@ -333,7 +332,7 @@ def get_version():
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'psutil', 'psutil Documentation',
[author], 1)
[author], 1),
]

# If true, show URL addresses after external links.
Expand Down
64 changes: 38 additions & 26 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,17 +317,16 @@ def _init(self, pid, _ignore_nsp=False):
pid = os.getpid()
else:
if not _PY3 and not isinstance(pid, (int, long)):
raise TypeError('pid must be an integer (got %r)' % pid)
msg = "pid must be an integer (got %r)" % pid
raise TypeError(msg)
if pid < 0:
raise ValueError('pid must be a positive integer (got %s)'
% pid)
msg = "pid must be a positive integer (got %s)" % pid
raise ValueError(msg)
try:
_psplatform.cext.check_pid_range(pid)
except OverflowError:
raise NoSuchProcess(
pid,
msg='process PID out of range (got %s)' % pid,
)
msg = "process PID out of range (got %s)" % pid
raise NoSuchProcess(pid, msg=msg)

self._pid = pid
self._name = None
Expand Down Expand Up @@ -359,7 +358,8 @@ def _init(self, pid, _ignore_nsp=False):
pass
except NoSuchProcess:
if not _ignore_nsp:
raise NoSuchProcess(pid, msg='process PID not found')
msg = "process PID not found"
raise NoSuchProcess(pid, msg=msg)
else:
self._gone = True
# This pair is supposed to identify a Process instance
Expand Down Expand Up @@ -523,13 +523,16 @@ def as_dict(self, attrs=None, ad_value=None):
valid_names = _as_dict_attrnames
if attrs is not None:
if not isinstance(attrs, (list, tuple, set, frozenset)):
raise TypeError("invalid attrs type %s" % type(attrs))
msg = "invalid attrs type %s" % type(attrs)
raise TypeError(msg)
attrs = set(attrs)
invalid_names = attrs - valid_names
if invalid_names:
raise ValueError("invalid attr name%s %s" % (
msg = "invalid attr name%s %s" % (
"s" if len(invalid_names) > 1 else "",
", ".join(map(repr, invalid_names))))
", ".join(map(repr, invalid_names)),
)
raise ValueError(msg)

retdict = {}
ls = attrs or valid_names
Expand Down Expand Up @@ -1006,7 +1009,8 @@ def cpu_percent(self, interval=None):
"""
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
msg = "interval is not positive (got %r)" % interval
raise ValueError(msg)
num_cpus = cpu_count() or 1

def timer():
Expand Down Expand Up @@ -1115,8 +1119,10 @@ def memory_percent(self, memtype="rss"):
"""
valid_types = list(_psplatform.pfullmem._fields)
if memtype not in valid_types:
raise ValueError("invalid memtype %r; valid types are %r" % (
memtype, tuple(valid_types)))
msg = "invalid memtype %r; valid types are %r" % (
memtype, tuple(valid_types),
)
raise ValueError(msg)
fun = self.memory_info if memtype in _psplatform.pmem._fields else \
self.memory_full_info
metrics = fun()
Expand All @@ -1126,10 +1132,11 @@ def memory_percent(self, memtype="rss"):
total_phymem = _TOTAL_PHYMEM or virtual_memory().total
if not total_phymem > 0:
# we should never get here
raise ValueError(
"can't calculate process memory percent because "
"total physical system memory is not positive (%r)"
% total_phymem)
msg = (
"can't calculate process memory percent because total physical"
" system memory is not positive (%r)" % (total_phymem)
)
raise ValueError(msg)
return (value / float(total_phymem)) * 100

if hasattr(_psplatform.Process, "memory_maps"):
Expand Down Expand Up @@ -1380,8 +1387,10 @@ def __getattribute__(self, name):
try:
return object.__getattribute__(self.__subproc, name)
except AttributeError:
raise AttributeError("%s instance has no attribute '%s'"
% (self.__class__.__name__, name))
msg = "%s instance has no attribute '%s'" % (
self.__class__.__name__, name,
)
raise AttributeError(msg)

def wait(self, timeout=None):
if self.__subproc.returncode is not None:
Expand Down Expand Up @@ -1558,7 +1567,8 @@ def check_gone(proc, timeout):
gone = set()
alive = set(procs)
if callback is not None and not callable(callback):
raise TypeError("callback %r is not a callable" % callable)
msg = "callback %r is not a callable" % callback
raise TypeError(msg)
if timeout is not None:
deadline = _timer() + timeout

Expand Down Expand Up @@ -1650,15 +1660,15 @@ def cpu_times(percpu=False):

try:
_last_cpu_times = {threading.current_thread().ident: cpu_times()}
except Exception:
except Exception: # noqa: BLE001
# Don't want to crash at import time.
_last_cpu_times = {}

try:
_last_per_cpu_times = {
threading.current_thread().ident: cpu_times(percpu=True)
threading.current_thread().ident: cpu_times(percpu=True),
}
except Exception:
except Exception: # noqa: BLE001
# Don't want to crash at import time.
_last_per_cpu_times = {}

Expand Down Expand Up @@ -1757,7 +1767,8 @@ def cpu_percent(interval=None, percpu=False):
tid = threading.current_thread().ident
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
msg = "interval is not positive (got %r)" % interval
raise ValueError(msg)

def calculate(t1, t2):
times_delta = _cpu_times_deltas(t1, t2)
Expand Down Expand Up @@ -1816,7 +1827,8 @@ def cpu_times_percent(interval=None, percpu=False):
tid = threading.current_thread().ident
blocking = interval is not None and interval > 0.0
if interval is not None and interval < 0:
raise ValueError("interval is not positive (got %r)" % interval)
msg = "interval is not positive (got %r)" % interval
raise ValueError(msg)

def calculate(t1, t2):
nums = []
Expand Down
8 changes: 4 additions & 4 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ def wrapper(*args, **kwargs):
except KeyError:
try:
ret = cache[key] = fun(*args, **kwargs)
except Exception as err:
except Exception as err: # noqa: BLE001
raise raise_from(err, None)
return ret

Expand Down Expand Up @@ -482,14 +482,14 @@ def wrapper(self):
# case 2: we never entered oneshot() ctx
try:
return fun(self)
except Exception as err:
except Exception as err: # noqa: BLE001
raise raise_from(err, None)
except KeyError:
# case 3: we entered oneshot() ctx but there's no cache
# for this entry yet
try:
ret = fun(self)
except Exception as err:
except Exception as err: # noqa: BLE001
raise raise_from(err, None)
try:
self._cache[fun] = ret
Expand Down Expand Up @@ -866,7 +866,7 @@ def term_supports_colors(file=sys.stdout): # pragma: no cover
assert file.isatty()
curses.setupterm()
assert curses.tigetnum("colors") > 0
except Exception:
except Exception: # noqa: BLE001
return False
else:
return True
Expand Down
2 changes: 1 addition & 1 deletion psutil/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def get_terminal_size(fallback=(80, 24)):
res = struct.unpack(
'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234'))
return (res[1], res[0])
except Exception:
except Exception: # noqa: BLE001
return fallback


Expand Down
8 changes: 4 additions & 4 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
# connection status constants
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING"
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING",
]


Expand Down Expand Up @@ -154,7 +154,7 @@ class IOPriority(enum.IntEnum):
"08": _common.CONN_CLOSE_WAIT,
"09": _common.CONN_LAST_ACK,
"0A": _common.CONN_LISTEN,
"0B": _common.CONN_CLOSING
"0B": _common.CONN_CLOSING,
}


Expand Down Expand Up @@ -283,7 +283,7 @@ def set_scputimes_ntuple(procfs_path):

try:
set_scputimes_ntuple("/proc")
except Exception as err: # pragma: no cover
except Exception as err: # noqa: BLE001
# Don't want to crash at import time.
debug("ignoring exception on import: %r" % err)
scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
Expand Down Expand Up @@ -2033,7 +2033,7 @@ def get_blocks(lines, current_block):
data.get(b'Private_Dirty:', 0),
data.get(b'Referenced:', 0),
data.get(b'Anonymous:', 0),
data.get(b'Swap:', 0)
data.get(b'Swap:', 0),
))
return ls

Expand Down
3 changes: 2 additions & 1 deletion psutil/_psposix.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ def sleep(interval):
# WNOHANG flag was used and PID is still running.
interval = sleep(interval)
continue
elif os.WIFEXITED(status):

if os.WIFEXITED(status):
# Process terminated normally by calling exit(3) or _exit(2),
# or by returning from main(). The return value is the
# positive integer passed to *exit().
Expand Down
14 changes: 6 additions & 8 deletions psutil/_pswindows.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,14 +717,12 @@ def wrapper(self, *args, **kwargs):
time.sleep(delay)
delay = min(delay * 2, 0.04)
continue
else:
raise
else:
msg = (
"{} retried {} times, converted to AccessDenied as it's "
"still returning {}".format(fun, times, err)
)
raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
raise
msg = (
"{} retried {} times, converted to AccessDenied as it's still"
"returning {}".format(fun, times, err)
)
raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
return wrapper


Expand Down
6 changes: 3 additions & 3 deletions psutil/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def macos_version():
os.path.join(os.path.dirname(__file__), '..', '..'))
SCRIPTS_DIR = os.environ.get(
"PSUTIL_SCRIPTS_DIR",
os.path.join(ROOT_DIR, 'scripts')
os.path.join(ROOT_DIR, 'scripts'),
)
HERE = os.path.realpath(os.path.dirname(__file__))

Expand All @@ -217,7 +217,7 @@ def macos_version():
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
try:
HAS_BATTERY = HAS_SENSORS_BATTERY and bool(psutil.sensors_battery())
except Exception:
except Exception: # noqa: BLE001
HAS_BATTERY = False
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")
Expand All @@ -232,7 +232,7 @@ def attempt(exe):
try:
subprocess.check_call(
[exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
except subprocess.CalledProcessError:
return None
else:
return exe
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def _split_suite(suite):
for test in suite:
if test.countTestCases() == 0:
continue
elif isinstance(test, unittest.TestSuite):
if isinstance(test, unittest.TestSuite):
test_class = test._tests[0].__class__
elif isinstance(test, unittest.TestCase):
test_class = test
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def test_all(self):
meth = getattr(self, name)
try:
meth(value, info)
except Exception:
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)
Expand Down
2 changes: 1 addition & 1 deletion psutil/tests/test_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -1630,7 +1630,7 @@ def test_emulate_power_undetermined(self):
def open_mock(name, *args, **kwargs):
if name.startswith(
('/sys/class/power_supply/AC0/online',
'/sys/class/power_supply/AC/online')
'/sys/class/power_supply/AC/online'),
):
raise IOError(errno.ENOENT, "")
elif name.startswith("/sys/class/power_supply/BAT0/status"):
Expand Down
4 changes: 2 additions & 2 deletions psutil/tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,7 +647,7 @@ def test_memory_maps(self):
value = getattr(nt, fname)
if fname == 'path':
continue
elif fname in ('addr', 'perms'):
if fname in ('addr', 'perms'):
assert value, value
else:
self.assertIsInstance(value, (int, long))
Expand Down Expand Up @@ -1412,7 +1412,7 @@ def clean_dict(d):
@unittest.skipIf(not POSIX, "POSIX only")
@unittest.skipIf(
MACOS_11PLUS,
"macOS 11+ can't get another process environment, issue #2084"
"macOS 11+ can't get another process environment, issue #2084",
)
def test_weird_environ(self):
# environment variables can contain values without an equals sign
Expand Down
4 changes: 2 additions & 2 deletions psutil/tests/test_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ def test_memory_vms(self):
# bytes but funnily enough on certain platforms bytes are
# returned instead.
wmi_usage = int(w.PageFileUsage)
if (vms != wmi_usage) and (vms != wmi_usage * 1024):
if vms not in (wmi_usage, wmi_usage * 1024):
raise self.fail("wmi=%s, psutil=%s" % (wmi_usage, vms))

def test_create_time(self):
Expand Down Expand Up @@ -822,7 +822,7 @@ def test_win_service_iter(self):
"pause_pending",
"continue_pending",
"stop_pending",
"stopped"
"stopped",
])
for serv in psutil.win_service_iter():
data = serv.as_dict()
Expand Down
Loading

0 comments on commit 63e579f

Please sign in to comment.