3636 # jupyter_client < 5, use local now()
3737 now = datetime .now
3838
39- try :
40- import psutil
41- except ImportError :
42- psutil = None
43-
44- _NO_SUCH_PROCESS = () if psutil is None else psutil .NoSuchProcess
45-
4639import zmq
4740from IPython .core .error import StdinNotImplementedError
4841from jupyter_client .session import Session
6861from .iostream import OutStream
6962from .utils import LazyDict , _async_in_context
7063
64+ psutil : t .Any | None
65+ try :
66+ import psutil as _psutil
67+ except ImportError :
68+ psutil = None
69+ else :
70+ psutil = _psutil
71+
72+ if psutil is None :
73+ _NO_SUCH_PROCESS : tuple [type [BaseException ], ...] = ()
74+ else :
75+ _NO_SUCH_PROCESS = (psutil .NoSuchProcess ,)
76+
7177_AWAITABLE_MESSAGE : str = (
7278 "For consistency across implementations, it is recommended that `{func_name}`"
7379 " either be a coroutine function (`async def`) or return an awaitable object"
@@ -1189,8 +1195,7 @@ async def usage_request(self, stream, ident, parent):
11891195 # Ensure 1) self.processes is updated to only current subprocesses
11901196 # and 2) we reuse processes when possible (needed for accurate CPU)
11911197 self .processes = {
1192- process .pid : self .processes .get (process .pid , process ) # type:ignore[misc,call-overload]
1193- for process in all_processes
1198+ process .pid : self .processes .get (process .pid , process ) for process in all_processes
11941199 }
11951200 reply_content ["kernel_cpu" ] = sum (
11961201 [
@@ -1208,7 +1213,7 @@ async def usage_request(self, stream, ident, parent):
12081213 cpu_percent = psutil .cpu_percent ()
12091214 # https://psutil.readthedocs.io/en/latest/index.html?highlight=cpu#psutil.cpu_percent
12101215 # The first time cpu_percent is called it will return a meaningless 0.0 value which you are supposed to ignore.
1211- if cpu_percent is not None and cpu_percent != 0.0 : # type:ignore[redundant-expr]
1216+ if cpu_percent is not None and cpu_percent != 0.0 :
12121217 reply_content ["host_cpu_percent" ] = cpu_percent
12131218 reply_content ["cpu_count" ] = psutil .cpu_count (logical = True )
12141219 reply_content ["host_virtual_memory" ] = dict (psutil .virtual_memory ()._asdict ())
0 commit comments