Skip to content

Commit

Permalink
Run pyupgrade --py36-plus
Browse files Browse the repository at this point in the history
  • Loading branch information
mayeut committed Dec 2, 2023
1 parent 37c51e2 commit 9048714
Show file tree
Hide file tree
Showing 49 changed files with 221 additions and 260 deletions.
32 changes: 15 additions & 17 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
Expand All @@ -20,7 +18,6 @@
Works with Python versions 3.6+.
"""

from __future__ import division

import collections
import contextlib
Expand Down Expand Up @@ -225,7 +222,7 @@
msg = "version conflict: %r C extension " % _psplatform.cext.__file__
msg += "module was built for another version of psutil"
if hasattr(_psplatform.cext, 'version'):
msg += " (%s instead of %s)" % (
msg += " ({} instead of {})".format(
'.'.join([x for x in str(_psplatform.cext.version)]), __version__)
else:
msg += " (different than %s)" % __version__
Expand Down Expand Up @@ -271,7 +268,7 @@ def _pprint_secs(secs):
# =====================================================================


class Process(object): # noqa: UP004
class Process:
"""Represents an OS process with the given PID.
If PID is omitted current process PID (os.getpid()) is used.
Raise NoSuchProcess if PID does not exist.
Expand Down Expand Up @@ -380,10 +377,10 @@ def __str__(self):
info["exitcode"] = self._exitcode
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(["%s=%r" % (k, v) for k, v in info.items()]))
", ".join([f"{k}={v!r}" for k, v in info.items()]))

__repr__ = __str__

Expand Down Expand Up @@ -520,7 +517,7 @@ def as_dict(self, attrs=None, ad_value=None):
attrs = set(attrs)
invalid_names = attrs - valid_names
if invalid_names:
raise ValueError("invalid attr name%s %s" % (
raise ValueError("invalid attr name{} {}".format(
"s" if len(invalid_names) > 1 else "",
", ".join(map(repr, invalid_names))))

Expand Down Expand Up @@ -1108,8 +1105,9 @@ 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)))
raise ValueError(
"invalid memtype {!r}; valid types are {!r}".format(
memtype, tuple(valid_types)))
fun = self.memory_info if memtype in _psplatform.pmem._fields else \
self.memory_full_info
metrics = fun()
Expand Down Expand Up @@ -1293,11 +1291,11 @@ def wait(self, timeout=None):


# The valid attr names which can be processed by Process.as_dict().
_as_dict_attrnames = set(
[x for x in dir(Process) if not x.startswith('_') and x not in
['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
'memory_info_ex', 'oneshot']])
_as_dict_attrnames = {
x for x in dir(Process) if not x.startswith('_') and x not in [
'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
'memory_info_ex', 'oneshot']}


# =====================================================================
Expand Down Expand Up @@ -1379,7 +1377,7 @@ def __getattribute__(self, name):
def wait(self, timeout=None):
if self.__subproc.returncode is not None:
return self.__subproc.returncode
ret = super(Popen, self).wait(timeout) # noqa
ret = super().wait(timeout)
self.__subproc.returncode = ret
return ret

Expand Down Expand Up @@ -2418,7 +2416,7 @@ def test(): # pragma: no cover
print(line[:get_terminal_size()[0]]) # NOQA


del memoize_when_activated, division
del memoize_when_activated


if __name__ == "__main__":
Expand Down
23 changes: 11 additions & 12 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
# Note: this module is imported by setup.py so it should not import
# psutil or third-party modules.

from __future__ import division
from __future__ import print_function

import collections
import contextlib
Expand Down Expand Up @@ -282,16 +280,16 @@ def __str__(self):
info = self._infodict(("pid", "ppid", "name"))
if info:
details = "(%s)" % ", ".join(
["%s=%r" % (k, v) for k, v in info.items()])
[f"{k}={v!r}" for k, v in info.items()])
else:
details = None
return " ".join([x for x in (getattr(self, "msg", ""), details) if x])

def __repr__(self):
# invoked on `repr(Error)`
info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
details = ", ".join(["%s=%r" % (k, v) for k, v in info.items()])
return "psutil.%s(%s)" % (self.__class__.__name__, details)
details = ", ".join([f"{k}={v!r}" for k, v in info.items()])
return f"psutil.{self.__class__.__name__}({details})"


class NoSuchProcess(Error):
Expand Down Expand Up @@ -522,7 +520,7 @@ def supports_ipv6():
with contextlib.closing(sock):
sock.bind(("::1", 0))
return True
except socket.error:
except OSError:
return False


Expand Down Expand Up @@ -598,8 +596,9 @@ def deprecated_method(replacement):
'replcement' is the method name which will be called instead.
"""
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; "
f"use {replacement}() instead")
if fun.__doc__ is None:
fun.__doc__ = msg

Expand Down Expand Up @@ -766,7 +765,7 @@ def cat(fname, fallback=_DEFAULT, _open=open_text):
try:
with _open(fname) as f:
return f.read()
except (IOError, OSError):
except OSError:
return fallback


Expand Down Expand Up @@ -839,7 +838,7 @@ def hilite(s, color=None, bold=False): # pragma: no cover
attr.append(color)
if bold:
attr.append('1')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), s)
return '\x1b[{}m{}\x1b[0m'.format(';'.join(attr), s)


def print_color(
Expand All @@ -862,7 +861,7 @@ def print_color(
try:
color = colors[color]
except KeyError:
raise ValueError("invalid color %r; choose between %r" % (
raise ValueError("invalid color {!r}; choose between {!r}".format(
color, list(colors.keys())))
if bold and color <= 7:
color += 8
Expand All @@ -889,5 +888,5 @@ def debug(msg):
msg = "ignoring %s" % msg
else:
msg = "ignoring %r" % msg
print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA
print(f"psutil-debug [{fname}:{lineno}]> {msg}", # NOQA
file=sys.stderr)
14 changes: 7 additions & 7 deletions psutil/_psaix.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def cpu_count_cores():
stdout, stderr = (x.decode(sys.stdout.encoding)
for x in (stdout, stderr))
if p.returncode != 0:
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
raise RuntimeError(f"{cmd!r} command error\n{stderr}")
processors = stdout.strip().splitlines()
return len(processors) or None

Expand Down Expand Up @@ -228,7 +228,7 @@ def net_if_stats():
"""Get NIC stats (isup, duplex, speed, mtu)."""
duplex_map = {"Full": NIC_DUPLEX_FULL,
"Half": NIC_DUPLEX_HALF}
names = set([x[0] for x in net_if_addrs()])
names = {x[0] for x in net_if_addrs()}
ret = {}
for name in names:
mtu = cext_posix.net_if_mtu(name)
Expand Down Expand Up @@ -417,7 +417,7 @@ def threads(self):
# is no longer there.
if not retlist:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
os.stat(f'{self._procfs_path}/{self.pid}')
return retlist

@wrap_exceptions
Expand All @@ -430,7 +430,7 @@ def connections(self, kind='inet'):
# is no longer there.
if not ret:
# will raise NSP if process is gone
os.stat('%s/%s' % (self._procfs_path, self.pid))
os.stat(f'{self._procfs_path}/{self.pid}')
return ret

@wrap_exceptions
Expand Down Expand Up @@ -476,10 +476,10 @@ def terminal(self):
def cwd(self):
procfs_path = self._procfs_path
try:
result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
result = os.readlink(f"{procfs_path}/{self.pid}/cwd")
return result.rstrip('/')
except FileNotFoundError:
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
os.stat(f"{procfs_path}/{self.pid}") # raise NSP or AD
return ""

@wrap_exceptions
Expand Down Expand Up @@ -522,7 +522,7 @@ def open_files(self):
def num_fds(self):
if self.pid == 0: # no /proc/0/fd
return 0
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd"))

@wrap_exceptions
def num_ctx_switches(self):
Expand Down
Loading

0 comments on commit 9048714

Please sign in to comment.