__init__.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """psutil is a cross-platform library for retrieving information on
  6. running processes and system utilization (CPU, memory, disks, network,
  7. sensors) in Python. Supported platforms:
  8. - Linux
  9. - Windows
  10. - macOS
  11. - FreeBSD
  12. - OpenBSD
  13. - NetBSD
  14. - Sun Solaris
  15. - AIX
  16. Works with Python versions 2.7 and 3.6+.
  17. """
  18. from __future__ import division
  19. import collections
  20. import contextlib
  21. import datetime
  22. import functools
  23. import os
  24. import signal
  25. import subprocess
  26. import sys
  27. import threading
  28. import time
  29. try:
  30. import pwd
  31. except ImportError:
  32. pwd = None
  33. from . import _common
  34. from ._common import AIX
  35. from ._common import BSD
  36. from ._common import CONN_CLOSE
  37. from ._common import CONN_CLOSE_WAIT
  38. from ._common import CONN_CLOSING
  39. from ._common import CONN_ESTABLISHED
  40. from ._common import CONN_FIN_WAIT1
  41. from ._common import CONN_FIN_WAIT2
  42. from ._common import CONN_LAST_ACK
  43. from ._common import CONN_LISTEN
  44. from ._common import CONN_NONE
  45. from ._common import CONN_SYN_RECV
  46. from ._common import CONN_SYN_SENT
  47. from ._common import CONN_TIME_WAIT
  48. from ._common import FREEBSD # NOQA
  49. from ._common import LINUX
  50. from ._common import MACOS
  51. from ._common import NETBSD # NOQA
  52. from ._common import NIC_DUPLEX_FULL
  53. from ._common import NIC_DUPLEX_HALF
  54. from ._common import NIC_DUPLEX_UNKNOWN
  55. from ._common import OPENBSD # NOQA
  56. from ._common import OSX # deprecated alias
  57. from ._common import POSIX # NOQA
  58. from ._common import POWER_TIME_UNKNOWN
  59. from ._common import POWER_TIME_UNLIMITED
  60. from ._common import STATUS_DEAD
  61. from ._common import STATUS_DISK_SLEEP
  62. from ._common import STATUS_IDLE
  63. from ._common import STATUS_LOCKED
  64. from ._common import STATUS_PARKED
  65. from ._common import STATUS_RUNNING
  66. from ._common import STATUS_SLEEPING
  67. from ._common import STATUS_STOPPED
  68. from ._common import STATUS_TRACING_STOP
  69. from ._common import STATUS_WAITING
  70. from ._common import STATUS_WAKING
  71. from ._common import STATUS_ZOMBIE
  72. from ._common import SUNOS
  73. from ._common import WINDOWS
  74. from ._common import AccessDenied
  75. from ._common import Error
  76. from ._common import NoSuchProcess
  77. from ._common import TimeoutExpired
  78. from ._common import ZombieProcess
  79. from ._common import memoize_when_activated
  80. from ._common import wrap_numbers as _wrap_numbers
  81. from ._compat import PY3 as _PY3
  82. from ._compat import PermissionError
  83. from ._compat import ProcessLookupError
  84. from ._compat import SubprocessTimeoutExpired as _SubprocessTimeoutExpired
  85. from ._compat import long
  86. if LINUX:
  87. # This is public API and it will be retrieved from _pslinux.py
  88. # via sys.modules.
  89. PROCFS_PATH = "/proc"
  90. from . import _pslinux as _psplatform
  91. from ._pslinux import IOPRIO_CLASS_BE # NOQA
  92. from ._pslinux import IOPRIO_CLASS_IDLE # NOQA
  93. from ._pslinux import IOPRIO_CLASS_NONE # NOQA
  94. from ._pslinux import IOPRIO_CLASS_RT # NOQA
  95. elif WINDOWS:
  96. from . import _pswindows as _psplatform
  97. from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # NOQA
  98. from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # NOQA
  99. from ._psutil_windows import HIGH_PRIORITY_CLASS # NOQA
  100. from ._psutil_windows import IDLE_PRIORITY_CLASS # NOQA
  101. from ._psutil_windows import NORMAL_PRIORITY_CLASS # NOQA
  102. from ._psutil_windows import REALTIME_PRIORITY_CLASS # NOQA
  103. from ._pswindows import CONN_DELETE_TCB # NOQA
  104. from ._pswindows import IOPRIO_HIGH # NOQA
  105. from ._pswindows import IOPRIO_LOW # NOQA
  106. from ._pswindows import IOPRIO_NORMAL # NOQA
  107. from ._pswindows import IOPRIO_VERYLOW # NOQA
  108. elif MACOS:
  109. from . import _psosx as _psplatform
  110. elif BSD:
  111. from . import _psbsd as _psplatform
  112. elif SUNOS:
  113. from . import _pssunos as _psplatform
  114. from ._pssunos import CONN_BOUND # NOQA
  115. from ._pssunos import CONN_IDLE # NOQA
  116. # This is public writable API which is read from _pslinux.py and
  117. # _pssunos.py via sys.modules.
  118. PROCFS_PATH = "/proc"
  119. elif AIX:
  120. from . import _psaix as _psplatform
  121. # This is public API and it will be retrieved from _pslinux.py
  122. # via sys.modules.
  123. PROCFS_PATH = "/proc"
  124. else: # pragma: no cover
  125. raise NotImplementedError('platform %s is not supported' % sys.platform)
  126. __all__ = [
  127. # exceptions
  128. "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
  129. "TimeoutExpired",
  130. # constants
  131. "version_info", "__version__",
  132. "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
  133. "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
  134. "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",
  135. "STATUS_PARKED",
  136. "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
  137. "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
  138. "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
  139. # "CONN_IDLE", "CONN_BOUND",
  140. "AF_LINK",
  141. "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
  142. "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
  143. "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
  144. "SUNOS", "WINDOWS", "AIX",
  145. # "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
  146. # "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
  147. # "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
  148. # "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
  149. # classes
  150. "Process", "Popen",
  151. # functions
  152. "pid_exists", "pids", "process_iter", "wait_procs", # proc
  153. "virtual_memory", "swap_memory", # memory
  154. "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
  155. "cpu_stats", # "cpu_freq", "getloadavg"
  156. "net_io_counters", "net_connections", "net_if_addrs", # network
  157. "net_if_stats",
  158. "disk_io_counters", "disk_partitions", "disk_usage", # disk
  159. # "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors
  160. "users", "boot_time", # others
  161. ]
  162. __all__.extend(_psplatform.__extra__all__)
  163. # Linux, FreeBSD
  164. if hasattr(_psplatform.Process, "rlimit"):
  165. # Populate global namespace with RLIM* constants.
  166. from . import _psutil_posix
  167. _globals = globals()
  168. _name = None
  169. for _name in dir(_psutil_posix):
  170. if _name.startswith('RLIM') and _name.isupper():
  171. _globals[_name] = getattr(_psutil_posix, _name)
  172. __all__.append(_name)
  173. del _globals, _name
  174. AF_LINK = _psplatform.AF_LINK
  175. __author__ = "Giampaolo Rodola'"
  176. __version__ = "5.9.7"
  177. version_info = tuple([int(num) for num in __version__.split('.')])
  178. _timer = getattr(time, 'monotonic', time.time)
  179. _TOTAL_PHYMEM = None
  180. _LOWEST_PID = None
  181. _SENTINEL = object()
  182. # Sanity check in case the user messed up with psutil installation
  183. # or did something weird with sys.path. In this case we might end
  184. # up importing a python module using a C extension module which
  185. # was compiled for a different version of psutil.
  186. # We want to prevent that by failing sooner rather than later.
  187. # See: https://github.com/giampaolo/psutil/issues/564
  188. if (int(__version__.replace('.', '')) !=
  189. getattr(_psplatform.cext, 'version', None)):
  190. msg = "version conflict: %r C extension " % _psplatform.cext.__file__
  191. msg += "module was built for another version of psutil"
  192. if hasattr(_psplatform.cext, 'version'):
  193. msg += " (%s instead of %s)" % (
  194. '.'.join([x for x in str(_psplatform.cext.version)]), __version__)
  195. else:
  196. msg += " (different than %s)" % __version__
  197. msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
  198. getattr(_psplatform.cext, "__file__",
  199. "the existing psutil install directory"))
  200. msg += " or clean the virtual env somehow, then reinstall"
  201. raise ImportError(msg)
  202. # =====================================================================
  203. # --- Utils
  204. # =====================================================================
  205. if hasattr(_psplatform, 'ppid_map'):
  206. # Faster version (Windows and Linux).
  207. _ppid_map = _psplatform.ppid_map
  208. else: # pragma: no cover
  209. def _ppid_map():
  210. """Return a {pid: ppid, ...} dict for all running processes in
  211. one shot. Used to speed up Process.children().
  212. """
  213. ret = {}
  214. for pid in pids():
  215. try:
  216. ret[pid] = _psplatform.Process(pid).ppid()
  217. except (NoSuchProcess, ZombieProcess):
  218. pass
  219. return ret
  220. def _pprint_secs(secs):
  221. """Format seconds in a human readable form."""
  222. now = time.time()
  223. secs_ago = int(now - secs)
  224. fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S"
  225. return datetime.datetime.fromtimestamp(secs).strftime(fmt)
  226. # =====================================================================
  227. # --- Process class
  228. # =====================================================================
  229. class Process(object): # noqa: UP004
  230. """Represents an OS process with the given PID.
  231. If PID is omitted current process PID (os.getpid()) is used.
  232. Raise NoSuchProcess if PID does not exist.
  233. Note that most of the methods of this class do not make sure
  234. the PID of the process being queried has been reused over time.
  235. That means you might end up retrieving an information referring
  236. to another process in case the original one this instance
  237. refers to is gone in the meantime.
  238. The only exceptions for which process identity is pre-emptively
  239. checked and guaranteed are:
  240. - parent()
  241. - children()
  242. - nice() (set)
  243. - ionice() (set)
  244. - rlimit() (set)
  245. - cpu_affinity (set)
  246. - suspend()
  247. - resume()
  248. - send_signal()
  249. - terminate()
  250. - kill()
  251. To prevent this problem for all other methods you can:
  252. - use is_running() before querying the process
  253. - if you're continuously iterating over a set of Process
  254. instances use process_iter() which pre-emptively checks
  255. process identity for every yielded instance
  256. """
  257. def __init__(self, pid=None):
  258. self._init(pid)
  259. def _init(self, pid, _ignore_nsp=False):
  260. if pid is None:
  261. pid = os.getpid()
  262. else:
  263. if not _PY3 and not isinstance(pid, (int, long)):
  264. raise TypeError('pid must be an integer (got %r)' % pid)
  265. if pid < 0:
  266. raise ValueError('pid must be a positive integer (got %s)'
  267. % pid)
  268. try:
  269. _psplatform.cext.check_pid_range(pid)
  270. except OverflowError:
  271. raise NoSuchProcess(
  272. pid,
  273. msg='process PID out of range (got %s)' % pid,
  274. )
  275. self._pid = pid
  276. self._name = None
  277. self._exe = None
  278. self._create_time = None
  279. self._gone = False
  280. self._pid_reused = False
  281. self._hash = None
  282. self._lock = threading.RLock()
  283. # used for caching on Windows only (on POSIX ppid may change)
  284. self._ppid = None
  285. # platform-specific modules define an _psplatform.Process
  286. # implementation class
  287. self._proc = _psplatform.Process(pid)
  288. self._last_sys_cpu_times = None
  289. self._last_proc_cpu_times = None
  290. self._exitcode = _SENTINEL
  291. # cache creation time for later use in is_running() method
  292. try:
  293. self.create_time()
  294. except AccessDenied:
  295. # We should never get here as AFAIK we're able to get
  296. # process creation time on all platforms even as a
  297. # limited user.
  298. pass
  299. except ZombieProcess:
  300. # Zombies can still be queried by this class (although
  301. # not always) and pids() return them so just go on.
  302. pass
  303. except NoSuchProcess:
  304. if not _ignore_nsp:
  305. raise NoSuchProcess(pid, msg='process PID not found')
  306. else:
  307. self._gone = True
  308. # This pair is supposed to identify a Process instance
  309. # univocally over time (the PID alone is not enough as
  310. # it might refer to a process whose PID has been reused).
  311. # This will be used later in __eq__() and is_running().
  312. self._ident = (self.pid, self._create_time)
  313. def __str__(self):
  314. info = collections.OrderedDict()
  315. info["pid"] = self.pid
  316. if self._name:
  317. info['name'] = self._name
  318. with self.oneshot():
  319. try:
  320. info["name"] = self.name()
  321. info["status"] = self.status()
  322. except ZombieProcess:
  323. info["status"] = "zombie"
  324. except NoSuchProcess:
  325. info["status"] = "terminated"
  326. except AccessDenied:
  327. pass
  328. if self._exitcode not in (_SENTINEL, None):
  329. info["exitcode"] = self._exitcode
  330. if self._create_time is not None:
  331. info['started'] = _pprint_secs(self._create_time)
  332. return "%s.%s(%s)" % (
  333. self.__class__.__module__,
  334. self.__class__.__name__,
  335. ", ".join(["%s=%r" % (k, v) for k, v in info.items()]))
  336. __repr__ = __str__
  337. def __eq__(self, other):
  338. # Test for equality with another Process object based
  339. # on PID and creation time.
  340. if not isinstance(other, Process):
  341. return NotImplemented
  342. if OPENBSD or NETBSD: # pragma: no cover
  343. # Zombie processes on Open/NetBSD have a creation time of
  344. # 0.0. This covers the case when a process started normally
  345. # (so it has a ctime), then it turned into a zombie. It's
  346. # important to do this because is_running() depends on
  347. # __eq__.
  348. pid1, ctime1 = self._ident
  349. pid2, ctime2 = other._ident
  350. if pid1 == pid2:
  351. if ctime1 and not ctime2:
  352. try:
  353. return self.status() == STATUS_ZOMBIE
  354. except Error:
  355. pass
  356. return self._ident == other._ident
  357. def __ne__(self, other):
  358. return not self == other
  359. def __hash__(self):
  360. if self._hash is None:
  361. self._hash = hash(self._ident)
  362. return self._hash
  363. def _raise_if_pid_reused(self):
  364. """Raises NoSuchProcess in case process PID has been reused."""
  365. if not self.is_running() and self._pid_reused:
  366. # We may directly raise NSP in here already if PID is just
  367. # not running, but I prefer NSP to be raised naturally by
  368. # the actual Process API call. This way unit tests will tell
  369. # us if the API is broken (aka don't raise NSP when it
  370. # should). We also remain consistent with all other "get"
  371. # APIs which don't use _raise_if_pid_reused().
  372. msg = "process no longer exists and its PID has been reused"
  373. raise NoSuchProcess(self.pid, self._name, msg=msg)
  374. @property
  375. def pid(self):
  376. """The process PID."""
  377. return self._pid
  378. # --- utility methods
  379. @contextlib.contextmanager
  380. def oneshot(self):
  381. """Utility context manager which considerably speeds up the
  382. retrieval of multiple process information at the same time.
  383. Internally different process info (e.g. name, ppid, uids,
  384. gids, ...) may be fetched by using the same routine, but
  385. only one information is returned and the others are discarded.
  386. When using this context manager the internal routine is
  387. executed once (in the example below on name()) and the
  388. other info are cached.
  389. The cache is cleared when exiting the context manager block.
  390. The advice is to use this every time you retrieve more than
  391. one information about the process. If you're lucky, you'll
  392. get a hell of a speedup.
  393. >>> import psutil
  394. >>> p = psutil.Process()
  395. >>> with p.oneshot():
  396. ... p.name() # collect multiple info
  397. ... p.cpu_times() # return cached value
  398. ... p.cpu_percent() # return cached value
  399. ... p.create_time() # return cached value
  400. ...
  401. >>>
  402. """
  403. with self._lock:
  404. if hasattr(self, "_cache"):
  405. # NOOP: this covers the use case where the user enters the
  406. # context twice:
  407. #
  408. # >>> with p.oneshot():
  409. # ... with p.oneshot():
  410. # ...
  411. #
  412. # Also, since as_dict() internally uses oneshot()
  413. # I expect that the code below will be a pretty common
  414. # "mistake" that the user will make, so let's guard
  415. # against that:
  416. #
  417. # >>> with p.oneshot():
  418. # ... p.as_dict()
  419. # ...
  420. yield
  421. else:
  422. try:
  423. # cached in case cpu_percent() is used
  424. self.cpu_times.cache_activate(self)
  425. # cached in case memory_percent() is used
  426. self.memory_info.cache_activate(self)
  427. # cached in case parent() is used
  428. self.ppid.cache_activate(self)
  429. # cached in case username() is used
  430. if POSIX:
  431. self.uids.cache_activate(self)
  432. # specific implementation cache
  433. self._proc.oneshot_enter()
  434. yield
  435. finally:
  436. self.cpu_times.cache_deactivate(self)
  437. self.memory_info.cache_deactivate(self)
  438. self.ppid.cache_deactivate(self)
  439. if POSIX:
  440. self.uids.cache_deactivate(self)
  441. self._proc.oneshot_exit()
  442. def as_dict(self, attrs=None, ad_value=None):
  443. """Utility method returning process information as a
  444. hashable dictionary.
  445. If *attrs* is specified it must be a list of strings
  446. reflecting available Process class' attribute names
  447. (e.g. ['cpu_times', 'name']) else all public (read
  448. only) attributes are assumed.
  449. *ad_value* is the value which gets assigned in case
  450. AccessDenied or ZombieProcess exception is raised when
  451. retrieving that particular process information.
  452. """
  453. valid_names = _as_dict_attrnames
  454. if attrs is not None:
  455. if not isinstance(attrs, (list, tuple, set, frozenset)):
  456. raise TypeError("invalid attrs type %s" % type(attrs))
  457. attrs = set(attrs)
  458. invalid_names = attrs - valid_names
  459. if invalid_names:
  460. raise ValueError("invalid attr name%s %s" % (
  461. "s" if len(invalid_names) > 1 else "",
  462. ", ".join(map(repr, invalid_names))))
  463. retdict = {}
  464. ls = attrs or valid_names
  465. with self.oneshot():
  466. for name in ls:
  467. try:
  468. if name == 'pid':
  469. ret = self.pid
  470. else:
  471. meth = getattr(self, name)
  472. ret = meth()
  473. except (AccessDenied, ZombieProcess):
  474. ret = ad_value
  475. except NotImplementedError:
  476. # in case of not implemented functionality (may happen
  477. # on old or exotic systems) we want to crash only if
  478. # the user explicitly asked for that particular attr
  479. if attrs:
  480. raise
  481. continue
  482. retdict[name] = ret
  483. return retdict
  484. def parent(self):
  485. """Return the parent process as a Process object pre-emptively
  486. checking whether PID has been reused.
  487. If no parent is known return None.
  488. """
  489. lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
  490. if self.pid == lowest_pid:
  491. return None
  492. ppid = self.ppid()
  493. if ppid is not None:
  494. ctime = self.create_time()
  495. try:
  496. parent = Process(ppid)
  497. if parent.create_time() <= ctime:
  498. return parent
  499. # ...else ppid has been reused by another process
  500. except NoSuchProcess:
  501. pass
  502. def parents(self):
  503. """Return the parents of this process as a list of Process
  504. instances. If no parents are known return an empty list.
  505. """
  506. parents = []
  507. proc = self.parent()
  508. while proc is not None:
  509. parents.append(proc)
  510. proc = proc.parent()
  511. return parents
  512. def is_running(self):
  513. """Return whether this process is running.
  514. It also checks if PID has been reused by another process in
  515. which case return False.
  516. """
  517. if self._gone or self._pid_reused:
  518. return False
  519. try:
  520. # Checking if PID is alive is not enough as the PID might
  521. # have been reused by another process: we also want to
  522. # verify process identity.
  523. # Process identity / uniqueness over time is guaranteed by
  524. # (PID + creation time) and that is verified in __eq__.
  525. self._pid_reused = self != Process(self.pid)
  526. return not self._pid_reused
  527. except ZombieProcess:
  528. # We should never get here as it's already handled in
  529. # Process.__init__; here just for extra safety.
  530. return True
  531. except NoSuchProcess:
  532. self._gone = True
  533. return False
  534. # --- actual API
  535. @memoize_when_activated
  536. def ppid(self):
  537. """The process parent PID.
  538. On Windows the return value is cached after first call.
  539. """
  540. # On POSIX we don't want to cache the ppid as it may unexpectedly
  541. # change to 1 (init) in case this process turns into a zombie:
  542. # https://github.com/giampaolo/psutil/issues/321
  543. # http://stackoverflow.com/questions/356722/
  544. # XXX should we check creation time here rather than in
  545. # Process.parent()?
  546. self._raise_if_pid_reused()
  547. if POSIX:
  548. return self._proc.ppid()
  549. else: # pragma: no cover
  550. self._ppid = self._ppid or self._proc.ppid()
  551. return self._ppid
  552. def name(self):
  553. """The process name. The return value is cached after first call."""
  554. # Process name is only cached on Windows as on POSIX it may
  555. # change, see:
  556. # https://github.com/giampaolo/psutil/issues/692
  557. if WINDOWS and self._name is not None:
  558. return self._name
  559. name = self._proc.name()
  560. if POSIX and len(name) >= 15:
  561. # On UNIX the name gets truncated to the first 15 characters.
  562. # If it matches the first part of the cmdline we return that
  563. # one instead because it's usually more explicative.
  564. # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
  565. try:
  566. cmdline = self.cmdline()
  567. except (AccessDenied, ZombieProcess):
  568. # Just pass and return the truncated name: it's better
  569. # than nothing. Note: there are actual cases where a
  570. # zombie process can return a name() but not a
  571. # cmdline(), see:
  572. # https://github.com/giampaolo/psutil/issues/2239
  573. pass
  574. else:
  575. if cmdline:
  576. extended_name = os.path.basename(cmdline[0])
  577. if extended_name.startswith(name):
  578. name = extended_name
  579. self._name = name
  580. self._proc._name = name
  581. return name
  582. def exe(self):
  583. """The process executable as an absolute path.
  584. May also be an empty string.
  585. The return value is cached after first call.
  586. """
  587. def guess_it(fallback):
  588. # try to guess exe from cmdline[0] in absence of a native
  589. # exe representation
  590. cmdline = self.cmdline()
  591. if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
  592. exe = cmdline[0] # the possible exe
  593. # Attempt to guess only in case of an absolute path.
  594. # It is not safe otherwise as the process might have
  595. # changed cwd.
  596. if (os.path.isabs(exe) and
  597. os.path.isfile(exe) and
  598. os.access(exe, os.X_OK)):
  599. return exe
  600. if isinstance(fallback, AccessDenied):
  601. raise fallback
  602. return fallback
  603. if self._exe is None:
  604. try:
  605. exe = self._proc.exe()
  606. except AccessDenied as err:
  607. return guess_it(fallback=err)
  608. else:
  609. if not exe:
  610. # underlying implementation can legitimately return an
  611. # empty string; if that's the case we don't want to
  612. # raise AD while guessing from the cmdline
  613. try:
  614. exe = guess_it(fallback=exe)
  615. except AccessDenied:
  616. pass
  617. self._exe = exe
  618. return self._exe
  619. def cmdline(self):
  620. """The command line this process has been called with."""
  621. return self._proc.cmdline()
  622. def status(self):
  623. """The process current status as a STATUS_* constant."""
  624. try:
  625. return self._proc.status()
  626. except ZombieProcess:
  627. return STATUS_ZOMBIE
  628. def username(self):
  629. """The name of the user that owns the process.
  630. On UNIX this is calculated by using *real* process uid.
  631. """
  632. if POSIX:
  633. if pwd is None:
  634. # might happen if python was installed from sources
  635. msg = "requires pwd module shipped with standard python"
  636. raise ImportError(msg)
  637. real_uid = self.uids().real
  638. try:
  639. return pwd.getpwuid(real_uid).pw_name
  640. except KeyError:
  641. # the uid can't be resolved by the system
  642. return str(real_uid)
  643. else:
  644. return self._proc.username()
  645. def create_time(self):
  646. """The process creation time as a floating point number
  647. expressed in seconds since the epoch.
  648. The return value is cached after first call.
  649. """
  650. if self._create_time is None:
  651. self._create_time = self._proc.create_time()
  652. return self._create_time
  653. def cwd(self):
  654. """Process current working directory as an absolute path."""
  655. return self._proc.cwd()
  656. def nice(self, value=None):
  657. """Get or set process niceness (priority)."""
  658. if value is None:
  659. return self._proc.nice_get()
  660. else:
  661. self._raise_if_pid_reused()
  662. self._proc.nice_set(value)
  663. if POSIX:
  664. @memoize_when_activated
  665. def uids(self):
  666. """Return process UIDs as a (real, effective, saved)
  667. namedtuple.
  668. """
  669. return self._proc.uids()
  670. def gids(self):
  671. """Return process GIDs as a (real, effective, saved)
  672. namedtuple.
  673. """
  674. return self._proc.gids()
  675. def terminal(self):
  676. """The terminal associated with this process, if any,
  677. else None.
  678. """
  679. return self._proc.terminal()
  680. def num_fds(self):
  681. """Return the number of file descriptors opened by this
  682. process (POSIX only).
  683. """
  684. return self._proc.num_fds()
  685. # Linux, BSD, AIX and Windows only
  686. if hasattr(_psplatform.Process, "io_counters"):
  687. def io_counters(self):
  688. """Return process I/O statistics as a
  689. (read_count, write_count, read_bytes, write_bytes)
  690. namedtuple.
  691. Those are the number of read/write calls performed and the
  692. amount of bytes read and written by the process.
  693. """
  694. return self._proc.io_counters()
  695. # Linux and Windows
  696. if hasattr(_psplatform.Process, "ionice_get"):
  697. def ionice(self, ioclass=None, value=None):
  698. """Get or set process I/O niceness (priority).
  699. On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
  700. *value* is a number which goes from 0 to 7. The higher the
  701. value, the lower the I/O priority of the process.
  702. On Windows only *ioclass* is used and it can be set to 2
  703. (normal), 1 (low) or 0 (very low).
  704. Available on Linux and Windows > Vista only.
  705. """
  706. if ioclass is None:
  707. if value is not None:
  708. msg = "'ioclass' argument must be specified"
  709. raise ValueError(msg)
  710. return self._proc.ionice_get()
  711. else:
  712. self._raise_if_pid_reused()
  713. return self._proc.ionice_set(ioclass, value)
  714. # Linux / FreeBSD only
  715. if hasattr(_psplatform.Process, "rlimit"):
  716. def rlimit(self, resource, limits=None):
  717. """Get or set process resource limits as a (soft, hard)
  718. tuple.
  719. *resource* is one of the RLIMIT_* constants.
  720. *limits* is supposed to be a (soft, hard) tuple.
  721. See "man prlimit" for further info.
  722. Available on Linux and FreeBSD only.
  723. """
  724. if limits is not None:
  725. self._raise_if_pid_reused()
  726. return self._proc.rlimit(resource, limits)
  727. # Windows, Linux and FreeBSD only
  728. if hasattr(_psplatform.Process, "cpu_affinity_get"):
  729. def cpu_affinity(self, cpus=None):
  730. """Get or set process CPU affinity.
  731. If specified, *cpus* must be a list of CPUs for which you
  732. want to set the affinity (e.g. [0, 1]).
  733. If an empty list is passed, all egible CPUs are assumed
  734. (and set).
  735. (Windows, Linux and BSD only).
  736. """
  737. if cpus is None:
  738. return sorted(set(self._proc.cpu_affinity_get()))
  739. else:
  740. self._raise_if_pid_reused()
  741. if not cpus:
  742. if hasattr(self._proc, "_get_eligible_cpus"):
  743. cpus = self._proc._get_eligible_cpus()
  744. else:
  745. cpus = tuple(range(len(cpu_times(percpu=True))))
  746. self._proc.cpu_affinity_set(list(set(cpus)))
  747. # Linux, FreeBSD, SunOS
  748. if hasattr(_psplatform.Process, "cpu_num"):
  749. def cpu_num(self):
  750. """Return what CPU this process is currently running on.
  751. The returned number should be <= psutil.cpu_count()
  752. and <= len(psutil.cpu_percent(percpu=True)).
  753. It may be used in conjunction with
  754. psutil.cpu_percent(percpu=True) to observe the system
  755. workload distributed across CPUs.
  756. """
  757. return self._proc.cpu_num()
  758. # All platforms has it, but maybe not in the future.
  759. if hasattr(_psplatform.Process, "environ"):
  760. def environ(self):
  761. """The environment variables of the process as a dict. Note: this
  762. might not reflect changes made after the process started.
  763. """
  764. return self._proc.environ()
  765. if WINDOWS:
  766. def num_handles(self):
  767. """Return the number of handles opened by this process
  768. (Windows only).
  769. """
  770. return self._proc.num_handles()
  771. def num_ctx_switches(self):
  772. """Return the number of voluntary and involuntary context
  773. switches performed by this process.
  774. """
  775. return self._proc.num_ctx_switches()
  776. def num_threads(self):
  777. """Return the number of threads used by this process."""
  778. return self._proc.num_threads()
  779. if hasattr(_psplatform.Process, "threads"):
  780. def threads(self):
  781. """Return threads opened by process as a list of
  782. (id, user_time, system_time) namedtuples representing
  783. thread id and thread CPU times (user/system).
  784. On OpenBSD this method requires root access.
  785. """
  786. return self._proc.threads()
  787. def children(self, recursive=False):
  788. """Return the children of this process as a list of Process
  789. instances, pre-emptively checking whether PID has been reused.
  790. If *recursive* is True return all the parent descendants.
  791. Example (A == this process):
  792. A ─┐
  793. ├─ B (child) ─┐
  794. │ └─ X (grandchild) ─┐
  795. │ └─ Y (great grandchild)
  796. ├─ C (child)
  797. └─ D (child)
  798. >>> import psutil
  799. >>> p = psutil.Process()
  800. >>> p.children()
  801. B, C, D
  802. >>> p.children(recursive=True)
  803. B, X, Y, C, D
  804. Note that in the example above if process X disappears
  805. process Y won't be listed as the reference to process A
  806. is lost.
  807. """
  808. self._raise_if_pid_reused()
  809. ppid_map = _ppid_map()
  810. ret = []
  811. if not recursive:
  812. for pid, ppid in ppid_map.items():
  813. if ppid == self.pid:
  814. try:
  815. child = Process(pid)
  816. # if child happens to be older than its parent
  817. # (self) it means child's PID has been reused
  818. if self.create_time() <= child.create_time():
  819. ret.append(child)
  820. except (NoSuchProcess, ZombieProcess):
  821. pass
  822. else:
  823. # Construct a {pid: [child pids]} dict
  824. reverse_ppid_map = collections.defaultdict(list)
  825. for pid, ppid in ppid_map.items():
  826. reverse_ppid_map[ppid].append(pid)
  827. # Recursively traverse that dict, starting from self.pid,
  828. # such that we only call Process() on actual children
  829. seen = set()
  830. stack = [self.pid]
  831. while stack:
  832. pid = stack.pop()
  833. if pid in seen:
  834. # Since pids can be reused while the ppid_map is
  835. # constructed, there may be rare instances where
  836. # there's a cycle in the recorded process "tree".
  837. continue
  838. seen.add(pid)
  839. for child_pid in reverse_ppid_map[pid]:
  840. try:
  841. child = Process(child_pid)
  842. # if child happens to be older than its parent
  843. # (self) it means child's PID has been reused
  844. intime = self.create_time() <= child.create_time()
  845. if intime:
  846. ret.append(child)
  847. stack.append(child_pid)
  848. except (NoSuchProcess, ZombieProcess):
  849. pass
  850. return ret
  851. def cpu_percent(self, interval=None):
  852. """Return a float representing the current process CPU
  853. utilization as a percentage.
  854. When *interval* is 0.0 or None (default) compares process times
  855. to system CPU times elapsed since last call, returning
  856. immediately (non-blocking). That means that the first time
  857. this is called it will return a meaningful 0.0 value.
  858. When *interval* is > 0.0 compares process times to system CPU
  859. times elapsed before and after the interval (blocking).
  860. In this case is recommended for accuracy that this function
  861. be called with at least 0.1 seconds between calls.
  862. A value > 100.0 can be returned in case of processes running
  863. multiple threads on different CPU cores.
  864. The returned value is explicitly NOT split evenly between
  865. all available logical CPUs. This means that a busy loop process
  866. running on a system with 2 logical CPUs will be reported as
  867. having 100% CPU utilization instead of 50%.
  868. Examples:
  869. >>> import psutil
  870. >>> p = psutil.Process(os.getpid())
  871. >>> # blocking
  872. >>> p.cpu_percent(interval=1)
  873. 2.0
  874. >>> # non-blocking (percentage since last call)
  875. >>> p.cpu_percent(interval=None)
  876. 2.9
  877. >>>
  878. """
  879. blocking = interval is not None and interval > 0.0
  880. if interval is not None and interval < 0:
  881. raise ValueError("interval is not positive (got %r)" % interval)
  882. num_cpus = cpu_count() or 1
  883. def timer():
  884. return _timer() * num_cpus
  885. if blocking:
  886. st1 = timer()
  887. pt1 = self._proc.cpu_times()
  888. time.sleep(interval)
  889. st2 = timer()
  890. pt2 = self._proc.cpu_times()
  891. else:
  892. st1 = self._last_sys_cpu_times
  893. pt1 = self._last_proc_cpu_times
  894. st2 = timer()
  895. pt2 = self._proc.cpu_times()
  896. if st1 is None or pt1 is None:
  897. self._last_sys_cpu_times = st2
  898. self._last_proc_cpu_times = pt2
  899. return 0.0
  900. delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
  901. delta_time = st2 - st1
  902. # reset values for next call in case of interval == None
  903. self._last_sys_cpu_times = st2
  904. self._last_proc_cpu_times = pt2
  905. try:
  906. # This is the utilization split evenly between all CPUs.
  907. # E.g. a busy loop process on a 2-CPU-cores system at this
  908. # point is reported as 50% instead of 100%.
  909. overall_cpus_percent = ((delta_proc / delta_time) * 100)
  910. except ZeroDivisionError:
  911. # interval was too low
  912. return 0.0
  913. else:
  914. # Note 1:
  915. # in order to emulate "top" we multiply the value for the num
  916. # of CPU cores. This way the busy process will be reported as
  917. # having 100% (or more) usage.
  918. #
  919. # Note 2:
  920. # taskmgr.exe on Windows differs in that it will show 50%
  921. # instead.
  922. #
  923. # Note 3:
  924. # a percentage > 100 is legitimate as it can result from a
  925. # process with multiple threads running on different CPU
  926. # cores (top does the same), see:
  927. # http://stackoverflow.com/questions/1032357
  928. # https://github.com/giampaolo/psutil/issues/474
  929. single_cpu_percent = overall_cpus_percent * num_cpus
  930. return round(single_cpu_percent, 1)
  931. @memoize_when_activated
  932. def cpu_times(self):
  933. """Return a (user, system, children_user, children_system)
  934. namedtuple representing the accumulated process time, in
  935. seconds.
  936. This is similar to os.times() but per-process.
  937. On macOS and Windows children_user and children_system are
  938. always set to 0.
  939. """
  940. return self._proc.cpu_times()
  941. @memoize_when_activated
  942. def memory_info(self):
  943. """Return a namedtuple with variable fields depending on the
  944. platform, representing memory information about the process.
  945. The "portable" fields available on all platforms are `rss` and `vms`.
  946. All numbers are expressed in bytes.
  947. """
  948. return self._proc.memory_info()
  949. @_common.deprecated_method(replacement="memory_info")
  950. def memory_info_ex(self):
  951. return self.memory_info()
  952. def memory_full_info(self):
  953. """This method returns the same information as memory_info(),
  954. plus, on some platform (Linux, macOS, Windows), also provides
  955. additional metrics (USS, PSS and swap).
  956. The additional metrics provide a better representation of actual
  957. process memory usage.
  958. Namely USS is the memory which is unique to a process and which
  959. would be freed if the process was terminated right now.
  960. It does so by passing through the whole process address.
  961. As such it usually requires higher user privileges than
  962. memory_info() and is considerably slower.
  963. """
  964. return self._proc.memory_full_info()
  965. def memory_percent(self, memtype="rss"):
  966. """Compare process memory to total physical system memory and
  967. calculate process memory utilization as a percentage.
  968. *memtype* argument is a string that dictates what type of
  969. process memory you want to compare against (defaults to "rss").
  970. The list of available strings can be obtained like this:
  971. >>> psutil.Process().memory_info()._fields
  972. ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
  973. """
  974. valid_types = list(_psplatform.pfullmem._fields)
  975. if memtype not in valid_types:
  976. raise ValueError("invalid memtype %r; valid types are %r" % (
  977. memtype, tuple(valid_types)))
  978. fun = self.memory_info if memtype in _psplatform.pmem._fields else \
  979. self.memory_full_info
  980. metrics = fun()
  981. value = getattr(metrics, memtype)
  982. # use cached value if available
  983. total_phymem = _TOTAL_PHYMEM or virtual_memory().total
  984. if not total_phymem > 0:
  985. # we should never get here
  986. raise ValueError(
  987. "can't calculate process memory percent because "
  988. "total physical system memory is not positive (%r)"
  989. % total_phymem)
  990. return (value / float(total_phymem)) * 100
  991. if hasattr(_psplatform.Process, "memory_maps"):
  992. def memory_maps(self, grouped=True):
  993. """Return process' mapped memory regions as a list of namedtuples
  994. whose fields are variable depending on the platform.
  995. If *grouped* is True the mapped regions with the same 'path'
  996. are grouped together and the different memory fields are summed.
  997. If *grouped* is False every mapped region is shown as a single
  998. entity and the namedtuple will also include the mapped region's
  999. address space ('addr') and permission set ('perms').
  1000. """
  1001. it = self._proc.memory_maps()
  1002. if grouped:
  1003. d = {}
  1004. for tupl in it:
  1005. path = tupl[2]
  1006. nums = tupl[3:]
  1007. try:
  1008. d[path] = map(lambda x, y: x + y, d[path], nums)
  1009. except KeyError:
  1010. d[path] = nums
  1011. nt = _psplatform.pmmap_grouped
  1012. return [nt(path, *d[path]) for path in d] # NOQA
  1013. else:
  1014. nt = _psplatform.pmmap_ext
  1015. return [nt(*x) for x in it]
  1016. def open_files(self):
  1017. """Return files opened by process as a list of
  1018. (path, fd) namedtuples including the absolute file name
  1019. and file descriptor number.
  1020. """
  1021. return self._proc.open_files()
  1022. def connections(self, kind='inet'):
  1023. """Return socket connections opened by process as a list of
  1024. (fd, family, type, laddr, raddr, status) namedtuples.
  1025. The *kind* parameter filters for connections that match the
  1026. following criteria:
  1027. +------------+----------------------------------------------------+
  1028. | Kind Value | Connections using |
  1029. +------------+----------------------------------------------------+
  1030. | inet | IPv4 and IPv6 |
  1031. | inet4 | IPv4 |
  1032. | inet6 | IPv6 |
  1033. | tcp | TCP |
  1034. | tcp4 | TCP over IPv4 |
  1035. | tcp6 | TCP over IPv6 |
  1036. | udp | UDP |
  1037. | udp4 | UDP over IPv4 |
  1038. | udp6 | UDP over IPv6 |
  1039. | unix | UNIX socket (both UDP and TCP protocols) |
  1040. | all | the sum of all the possible families and protocols |
  1041. +------------+----------------------------------------------------+
  1042. """
  1043. return self._proc.connections(kind)
  1044. # --- signals
  1045. if POSIX:
  1046. def _send_signal(self, sig):
  1047. assert not self.pid < 0, self.pid
  1048. self._raise_if_pid_reused()
  1049. if self.pid == 0:
  1050. # see "man 2 kill"
  1051. msg = (
  1052. "preventing sending signal to process with PID 0 as it "
  1053. "would affect every process in the process group of the "
  1054. "calling process (os.getpid()) instead of PID 0"
  1055. )
  1056. raise ValueError(msg)
  1057. try:
  1058. os.kill(self.pid, sig)
  1059. except ProcessLookupError:
  1060. if OPENBSD and pid_exists(self.pid):
  1061. # We do this because os.kill() lies in case of
  1062. # zombie processes.
  1063. raise ZombieProcess(self.pid, self._name, self._ppid)
  1064. else:
  1065. self._gone = True
  1066. raise NoSuchProcess(self.pid, self._name)
  1067. except PermissionError:
  1068. raise AccessDenied(self.pid, self._name)
  1069. def send_signal(self, sig):
  1070. """Send a signal *sig* to process pre-emptively checking
  1071. whether PID has been reused (see signal module constants) .
  1072. On Windows only SIGTERM is valid and is treated as an alias
  1073. for kill().
  1074. """
  1075. if POSIX:
  1076. self._send_signal(sig)
  1077. else: # pragma: no cover
  1078. self._raise_if_pid_reused()
  1079. if sig != signal.SIGTERM and not self.is_running():
  1080. msg = "process no longer exists"
  1081. raise NoSuchProcess(self.pid, self._name, msg=msg)
  1082. self._proc.send_signal(sig)
  1083. def suspend(self):
  1084. """Suspend process execution with SIGSTOP pre-emptively checking
  1085. whether PID has been reused.
  1086. On Windows this has the effect of suspending all process threads.
  1087. """
  1088. if POSIX:
  1089. self._send_signal(signal.SIGSTOP)
  1090. else: # pragma: no cover
  1091. self._raise_if_pid_reused()
  1092. self._proc.suspend()
  1093. def resume(self):
  1094. """Resume process execution with SIGCONT pre-emptively checking
  1095. whether PID has been reused.
  1096. On Windows this has the effect of resuming all process threads.
  1097. """
  1098. if POSIX:
  1099. self._send_signal(signal.SIGCONT)
  1100. else: # pragma: no cover
  1101. self._raise_if_pid_reused()
  1102. self._proc.resume()
  1103. def terminate(self):
  1104. """Terminate the process with SIGTERM pre-emptively checking
  1105. whether PID has been reused.
  1106. On Windows this is an alias for kill().
  1107. """
  1108. if POSIX:
  1109. self._send_signal(signal.SIGTERM)
  1110. else: # pragma: no cover
  1111. self._raise_if_pid_reused()
  1112. self._proc.kill()
  1113. def kill(self):
  1114. """Kill the current process with SIGKILL pre-emptively checking
  1115. whether PID has been reused.
  1116. """
  1117. if POSIX:
  1118. self._send_signal(signal.SIGKILL)
  1119. else: # pragma: no cover
  1120. self._raise_if_pid_reused()
  1121. self._proc.kill()
  1122. def wait(self, timeout=None):
  1123. """Wait for process to terminate and, if process is a children
  1124. of os.getpid(), also return its exit code, else None.
  1125. On Windows there's no such limitation (exit code is always
  1126. returned).
  1127. If the process is already terminated immediately return None
  1128. instead of raising NoSuchProcess.
  1129. If *timeout* (in seconds) is specified and process is still
  1130. alive raise TimeoutExpired.
  1131. To wait for multiple Process(es) use psutil.wait_procs().
  1132. """
  1133. if timeout is not None and not timeout >= 0:
  1134. msg = "timeout must be a positive integer"
  1135. raise ValueError(msg)
  1136. if self._exitcode is not _SENTINEL:
  1137. return self._exitcode
  1138. self._exitcode = self._proc.wait(timeout)
  1139. return self._exitcode
  1140. # The valid attr names which can be processed by Process.as_dict().
  1141. _as_dict_attrnames = set(
  1142. [x for x in dir(Process) if not x.startswith('_') and x not in
  1143. {'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
  1144. 'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
  1145. 'memory_info_ex', 'oneshot'}])
  1146. # =====================================================================
  1147. # --- Popen class
  1148. # =====================================================================
  1149. class Popen(Process):
  1150. """Same as subprocess.Popen, but in addition it provides all
  1151. psutil.Process methods in a single class.
  1152. For the following methods which are common to both classes, psutil
  1153. implementation takes precedence:
  1154. * send_signal()
  1155. * terminate()
  1156. * kill()
  1157. This is done in order to avoid killing another process in case its
  1158. PID has been reused, fixing BPO-6973.
  1159. >>> import psutil
  1160. >>> from subprocess import PIPE
  1161. >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
  1162. >>> p.name()
  1163. 'python'
  1164. >>> p.uids()
  1165. user(real=1000, effective=1000, saved=1000)
  1166. >>> p.username()
  1167. 'giampaolo'
  1168. >>> p.communicate()
  1169. ('hi', None)
  1170. >>> p.terminate()
  1171. >>> p.wait(timeout=2)
  1172. 0
  1173. >>>
  1174. """
  1175. def __init__(self, *args, **kwargs):
  1176. # Explicitly avoid to raise NoSuchProcess in case the process
  1177. # spawned by subprocess.Popen terminates too quickly, see:
  1178. # https://github.com/giampaolo/psutil/issues/193
  1179. self.__subproc = subprocess.Popen(*args, **kwargs)
  1180. self._init(self.__subproc.pid, _ignore_nsp=True)
  1181. def __dir__(self):
  1182. return sorted(set(dir(Popen) + dir(subprocess.Popen)))
  1183. def __enter__(self):
  1184. if hasattr(self.__subproc, '__enter__'):
  1185. self.__subproc.__enter__()
  1186. return self
  1187. def __exit__(self, *args, **kwargs):
  1188. if hasattr(self.__subproc, '__exit__'):
  1189. return self.__subproc.__exit__(*args, **kwargs)
  1190. else:
  1191. if self.stdout:
  1192. self.stdout.close()
  1193. if self.stderr:
  1194. self.stderr.close()
  1195. try:
  1196. # Flushing a BufferedWriter may raise an error.
  1197. if self.stdin:
  1198. self.stdin.close()
  1199. finally:
  1200. # Wait for the process to terminate, to avoid zombies.
  1201. self.wait()
  1202. def __getattribute__(self, name):
  1203. try:
  1204. return object.__getattribute__(self, name)
  1205. except AttributeError:
  1206. try:
  1207. return object.__getattribute__(self.__subproc, name)
  1208. except AttributeError:
  1209. raise AttributeError("%s instance has no attribute '%s'"
  1210. % (self.__class__.__name__, name))
  1211. def wait(self, timeout=None):
  1212. if self.__subproc.returncode is not None:
  1213. return self.__subproc.returncode
  1214. ret = super(Popen, self).wait(timeout) # noqa
  1215. self.__subproc.returncode = ret
  1216. return ret
  1217. # =====================================================================
  1218. # --- system processes related functions
  1219. # =====================================================================
  1220. def pids():
  1221. """Return a list of current running PIDs."""
  1222. global _LOWEST_PID
  1223. ret = sorted(_psplatform.pids())
  1224. _LOWEST_PID = ret[0]
  1225. return ret
  1226. def pid_exists(pid):
  1227. """Return True if given PID exists in the current process list.
  1228. This is faster than doing "pid in psutil.pids()" and
  1229. should be preferred.
  1230. """
  1231. if pid < 0:
  1232. return False
  1233. elif pid == 0 and POSIX:
  1234. # On POSIX we use os.kill() to determine PID existence.
  1235. # According to "man 2 kill" PID 0 has a special meaning
  1236. # though: it refers to <<every process in the process
  1237. # group of the calling process>> and that is not we want
  1238. # to do here.
  1239. return pid in pids()
  1240. else:
  1241. return _psplatform.pid_exists(pid)
  1242. _pmap = {}
  1243. def process_iter(attrs=None, ad_value=None):
  1244. """Return a generator yielding a Process instance for all
  1245. running processes.
  1246. Every new Process instance is only created once and then cached
  1247. into an internal table which is updated every time this is used.
  1248. Cached Process instances are checked for identity so that you're
  1249. safe in case a PID has been reused by another process, in which
  1250. case the cached instance is updated.
  1251. The sorting order in which processes are yielded is based on
  1252. their PIDs.
  1253. *attrs* and *ad_value* have the same meaning as in
  1254. Process.as_dict(). If *attrs* is specified as_dict() is called
  1255. and the resulting dict is stored as a 'info' attribute attached
  1256. to returned Process instance.
  1257. If *attrs* is an empty list it will retrieve all process info
  1258. (slow).
  1259. """
  1260. global _pmap
  1261. def add(pid):
  1262. proc = Process(pid)
  1263. if attrs is not None:
  1264. proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
  1265. pmap[proc.pid] = proc
  1266. return proc
  1267. def remove(pid):
  1268. pmap.pop(pid, None)
  1269. pmap = _pmap.copy()
  1270. a = set(pids())
  1271. b = set(pmap.keys())
  1272. new_pids = a - b
  1273. gone_pids = b - a
  1274. for pid in gone_pids:
  1275. remove(pid)
  1276. try:
  1277. ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
  1278. for pid, proc in ls:
  1279. try:
  1280. if proc is None: # new process
  1281. yield add(pid)
  1282. else:
  1283. # use is_running() to check whether PID has been
  1284. # reused by another process in which case yield a
  1285. # new Process instance
  1286. if proc.is_running():
  1287. if attrs is not None:
  1288. proc.info = proc.as_dict(
  1289. attrs=attrs, ad_value=ad_value)
  1290. yield proc
  1291. else:
  1292. yield add(pid)
  1293. except NoSuchProcess:
  1294. remove(pid)
  1295. except AccessDenied:
  1296. # Process creation time can't be determined hence there's
  1297. # no way to tell whether the pid of the cached process
  1298. # has been reused. Just return the cached version.
  1299. if proc is None and pid in pmap:
  1300. try:
  1301. yield pmap[pid]
  1302. except KeyError:
  1303. # If we get here it is likely that 2 threads were
  1304. # using process_iter().
  1305. pass
  1306. else:
  1307. raise
  1308. finally:
  1309. _pmap = pmap
  1310. def wait_procs(procs, timeout=None, callback=None):
  1311. """Convenience function which waits for a list of processes to
  1312. terminate.
  1313. Return a (gone, alive) tuple indicating which processes
  1314. are gone and which ones are still alive.
  1315. The gone ones will have a new *returncode* attribute indicating
  1316. process exit status (may be None).
  1317. *callback* is a function which gets called every time a process
  1318. terminates (a Process instance is passed as callback argument).
  1319. Function will return as soon as all processes terminate or when
  1320. *timeout* occurs.
  1321. Differently from Process.wait() it will not raise TimeoutExpired if
  1322. *timeout* occurs.
  1323. Typical use case is:
  1324. - send SIGTERM to a list of processes
  1325. - give them some time to terminate
  1326. - send SIGKILL to those ones which are still alive
  1327. Example:
  1328. >>> def on_terminate(proc):
  1329. ... print("process {} terminated".format(proc))
  1330. ...
  1331. >>> for p in procs:
  1332. ... p.terminate()
  1333. ...
  1334. >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
  1335. >>> for p in alive:
  1336. ... p.kill()
  1337. """
  1338. def check_gone(proc, timeout):
  1339. try:
  1340. returncode = proc.wait(timeout=timeout)
  1341. except TimeoutExpired:
  1342. pass
  1343. except _SubprocessTimeoutExpired:
  1344. pass
  1345. else:
  1346. if returncode is not None or not proc.is_running():
  1347. # Set new Process instance attribute.
  1348. proc.returncode = returncode
  1349. gone.add(proc)
  1350. if callback is not None:
  1351. callback(proc)
  1352. if timeout is not None and not timeout >= 0:
  1353. msg = "timeout must be a positive integer, got %s" % timeout
  1354. raise ValueError(msg)
  1355. gone = set()
  1356. alive = set(procs)
  1357. if callback is not None and not callable(callback):
  1358. raise TypeError("callback %r is not a callable" % callable)
  1359. if timeout is not None:
  1360. deadline = _timer() + timeout
  1361. while alive:
  1362. if timeout is not None and timeout <= 0:
  1363. break
  1364. for proc in alive:
  1365. # Make sure that every complete iteration (all processes)
  1366. # will last max 1 sec.
  1367. # We do this because we don't want to wait too long on a
  1368. # single process: in case it terminates too late other
  1369. # processes may disappear in the meantime and their PID
  1370. # reused.
  1371. max_timeout = 1.0 / len(alive)
  1372. if timeout is not None:
  1373. timeout = min((deadline - _timer()), max_timeout)
  1374. if timeout <= 0:
  1375. break
  1376. check_gone(proc, timeout)
  1377. else:
  1378. check_gone(proc, max_timeout)
  1379. alive = alive - gone
  1380. if alive:
  1381. # Last attempt over processes survived so far.
  1382. # timeout == 0 won't make this function wait any further.
  1383. for proc in alive:
  1384. check_gone(proc, 0)
  1385. alive = alive - gone
  1386. return (list(gone), list(alive))
  1387. # =====================================================================
  1388. # --- CPU related functions
  1389. # =====================================================================
  1390. def cpu_count(logical=True):
  1391. """Return the number of logical CPUs in the system (same as
  1392. os.cpu_count() in Python 3.4).
  1393. If *logical* is False return the number of physical cores only
  1394. (e.g. hyper thread CPUs are excluded).
  1395. Return None if undetermined.
  1396. The return value is cached after first call.
  1397. If desired cache can be cleared like this:
  1398. >>> psutil.cpu_count.cache_clear()
  1399. """
  1400. if logical:
  1401. ret = _psplatform.cpu_count_logical()
  1402. else:
  1403. ret = _psplatform.cpu_count_cores()
  1404. if ret is not None and ret < 1:
  1405. ret = None
  1406. return ret
  1407. def cpu_times(percpu=False):
  1408. """Return system-wide CPU times as a namedtuple.
  1409. Every CPU time represents the seconds the CPU has spent in the
  1410. given mode. The namedtuple's fields availability varies depending on the
  1411. platform:
  1412. - user
  1413. - system
  1414. - idle
  1415. - nice (UNIX)
  1416. - iowait (Linux)
  1417. - irq (Linux, FreeBSD)
  1418. - softirq (Linux)
  1419. - steal (Linux >= 2.6.11)
  1420. - guest (Linux >= 2.6.24)
  1421. - guest_nice (Linux >= 3.2.0)
  1422. When *percpu* is True return a list of namedtuples for each CPU.
  1423. First element of the list refers to first CPU, second element
  1424. to second CPU and so on.
  1425. The order of the list is consistent across calls.
  1426. """
  1427. if not percpu:
  1428. return _psplatform.cpu_times()
  1429. else:
  1430. return _psplatform.per_cpu_times()
  1431. try:
  1432. _last_cpu_times = {threading.current_thread().ident: cpu_times()}
  1433. except Exception:
  1434. # Don't want to crash at import time.
  1435. _last_cpu_times = {}
  1436. try:
  1437. _last_per_cpu_times = {
  1438. threading.current_thread().ident: cpu_times(percpu=True)
  1439. }
  1440. except Exception:
  1441. # Don't want to crash at import time.
  1442. _last_per_cpu_times = {}
  1443. def _cpu_tot_time(times):
  1444. """Given a cpu_time() ntuple calculates the total CPU time
  1445. (including idle time).
  1446. """
  1447. tot = sum(times)
  1448. if LINUX:
  1449. # On Linux guest times are already accounted in "user" or
  1450. # "nice" times, so we subtract them from total.
  1451. # Htop does the same. References:
  1452. # https://github.com/giampaolo/psutil/pull/940
  1453. # http://unix.stackexchange.com/questions/178045
  1454. # https://github.com/torvalds/linux/blob/
  1455. # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
  1456. # cputime.c#L158
  1457. tot -= getattr(times, "guest", 0) # Linux 2.6.24+
  1458. tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+
  1459. return tot
  1460. def _cpu_busy_time(times):
  1461. """Given a cpu_time() ntuple calculates the busy CPU time.
  1462. We do so by subtracting all idle CPU times.
  1463. """
  1464. busy = _cpu_tot_time(times)
  1465. busy -= times.idle
  1466. # Linux: "iowait" is time during which the CPU does not do anything
  1467. # (waits for IO to complete). On Linux IO wait is *not* accounted
  1468. # in "idle" time so we subtract it. Htop does the same.
  1469. # References:
  1470. # https://github.com/torvalds/linux/blob/
  1471. # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
  1472. busy -= getattr(times, "iowait", 0)
  1473. return busy
  1474. def _cpu_times_deltas(t1, t2):
  1475. assert t1._fields == t2._fields, (t1, t2)
  1476. field_deltas = []
  1477. for field in _psplatform.scputimes._fields:
  1478. field_delta = getattr(t2, field) - getattr(t1, field)
  1479. # CPU times are always supposed to increase over time
  1480. # or at least remain the same and that's because time
  1481. # cannot go backwards.
  1482. # Surprisingly sometimes this might not be the case (at
  1483. # least on Windows and Linux), see:
  1484. # https://github.com/giampaolo/psutil/issues/392
  1485. # https://github.com/giampaolo/psutil/issues/645
  1486. # https://github.com/giampaolo/psutil/issues/1210
  1487. # Trim negative deltas to zero to ignore decreasing fields.
  1488. # top does the same. Reference:
  1489. # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
  1490. field_delta = max(0, field_delta)
  1491. field_deltas.append(field_delta)
  1492. return _psplatform.scputimes(*field_deltas)
  1493. def cpu_percent(interval=None, percpu=False):
  1494. """Return a float representing the current system-wide CPU
  1495. utilization as a percentage.
  1496. When *interval* is > 0.0 compares system CPU times elapsed before
  1497. and after the interval (blocking).
  1498. When *interval* is 0.0 or None compares system CPU times elapsed
  1499. since last call or module import, returning immediately (non
  1500. blocking). That means the first time this is called it will
  1501. return a meaningless 0.0 value which you should ignore.
  1502. In this case is recommended for accuracy that this function be
  1503. called with at least 0.1 seconds between calls.
  1504. When *percpu* is True returns a list of floats representing the
  1505. utilization as a percentage for each CPU.
  1506. First element of the list refers to first CPU, second element
  1507. to second CPU and so on.
  1508. The order of the list is consistent across calls.
  1509. Examples:
  1510. >>> # blocking, system-wide
  1511. >>> psutil.cpu_percent(interval=1)
  1512. 2.0
  1513. >>>
  1514. >>> # blocking, per-cpu
  1515. >>> psutil.cpu_percent(interval=1, percpu=True)
  1516. [2.0, 1.0]
  1517. >>>
  1518. >>> # non-blocking (percentage since last call)
  1519. >>> psutil.cpu_percent(interval=None)
  1520. 2.9
  1521. >>>
  1522. """
  1523. tid = threading.current_thread().ident
  1524. blocking = interval is not None and interval > 0.0
  1525. if interval is not None and interval < 0:
  1526. raise ValueError("interval is not positive (got %r)" % interval)
  1527. def calculate(t1, t2):
  1528. times_delta = _cpu_times_deltas(t1, t2)
  1529. all_delta = _cpu_tot_time(times_delta)
  1530. busy_delta = _cpu_busy_time(times_delta)
  1531. try:
  1532. busy_perc = (busy_delta / all_delta) * 100
  1533. except ZeroDivisionError:
  1534. return 0.0
  1535. else:
  1536. return round(busy_perc, 1)
  1537. # system-wide usage
  1538. if not percpu:
  1539. if blocking:
  1540. t1 = cpu_times()
  1541. time.sleep(interval)
  1542. else:
  1543. t1 = _last_cpu_times.get(tid) or cpu_times()
  1544. _last_cpu_times[tid] = cpu_times()
  1545. return calculate(t1, _last_cpu_times[tid])
  1546. # per-cpu usage
  1547. else:
  1548. ret = []
  1549. if blocking:
  1550. tot1 = cpu_times(percpu=True)
  1551. time.sleep(interval)
  1552. else:
  1553. tot1 = _last_per_cpu_times.get(tid) or cpu_times(percpu=True)
  1554. _last_per_cpu_times[tid] = cpu_times(percpu=True)
  1555. for t1, t2 in zip(tot1, _last_per_cpu_times[tid]):
  1556. ret.append(calculate(t1, t2))
  1557. return ret
  1558. # Use a separate dict for cpu_times_percent(), so it's independent from
  1559. # cpu_percent() and they can both be used within the same program.
  1560. _last_cpu_times_2 = _last_cpu_times.copy()
  1561. _last_per_cpu_times_2 = _last_per_cpu_times.copy()
  1562. def cpu_times_percent(interval=None, percpu=False):
  1563. """Same as cpu_percent() but provides utilization percentages
  1564. for each specific CPU time as is returned by cpu_times().
  1565. For instance, on Linux we'll get:
  1566. >>> cpu_times_percent()
  1567. cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
  1568. irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
  1569. >>>
  1570. *interval* and *percpu* arguments have the same meaning as in
  1571. cpu_percent().
  1572. """
  1573. tid = threading.current_thread().ident
  1574. blocking = interval is not None and interval > 0.0
  1575. if interval is not None and interval < 0:
  1576. raise ValueError("interval is not positive (got %r)" % interval)
  1577. def calculate(t1, t2):
  1578. nums = []
  1579. times_delta = _cpu_times_deltas(t1, t2)
  1580. all_delta = _cpu_tot_time(times_delta)
  1581. # "scale" is the value to multiply each delta with to get percentages.
  1582. # We use "max" to avoid division by zero (if all_delta is 0, then all
  1583. # fields are 0 so percentages will be 0 too. all_delta cannot be a
  1584. # fraction because cpu times are integers)
  1585. scale = 100.0 / max(1, all_delta)
  1586. for field_delta in times_delta:
  1587. field_perc = field_delta * scale
  1588. field_perc = round(field_perc, 1)
  1589. # make sure we don't return negative values or values over 100%
  1590. field_perc = min(max(0.0, field_perc), 100.0)
  1591. nums.append(field_perc)
  1592. return _psplatform.scputimes(*nums)
  1593. # system-wide usage
  1594. if not percpu:
  1595. if blocking:
  1596. t1 = cpu_times()
  1597. time.sleep(interval)
  1598. else:
  1599. t1 = _last_cpu_times_2.get(tid) or cpu_times()
  1600. _last_cpu_times_2[tid] = cpu_times()
  1601. return calculate(t1, _last_cpu_times_2[tid])
  1602. # per-cpu usage
  1603. else:
  1604. ret = []
  1605. if blocking:
  1606. tot1 = cpu_times(percpu=True)
  1607. time.sleep(interval)
  1608. else:
  1609. tot1 = _last_per_cpu_times_2.get(tid) or cpu_times(percpu=True)
  1610. _last_per_cpu_times_2[tid] = cpu_times(percpu=True)
  1611. for t1, t2 in zip(tot1, _last_per_cpu_times_2[tid]):
  1612. ret.append(calculate(t1, t2))
  1613. return ret
  1614. def cpu_stats():
  1615. """Return CPU statistics."""
  1616. return _psplatform.cpu_stats()
  1617. if hasattr(_psplatform, "cpu_freq"):
  1618. def cpu_freq(percpu=False):
  1619. """Return CPU frequency as a namedtuple including current,
  1620. min and max frequency expressed in Mhz.
  1621. If *percpu* is True and the system supports per-cpu frequency
  1622. retrieval (Linux only) a list of frequencies is returned for
  1623. each CPU. If not a list with one element is returned.
  1624. """
  1625. ret = _psplatform.cpu_freq()
  1626. if percpu:
  1627. return ret
  1628. else:
  1629. num_cpus = float(len(ret))
  1630. if num_cpus == 0:
  1631. return None
  1632. elif num_cpus == 1:
  1633. return ret[0]
  1634. else:
  1635. currs, mins, maxs = 0.0, 0.0, 0.0
  1636. set_none = False
  1637. for cpu in ret:
  1638. currs += cpu.current
  1639. # On Linux if /proc/cpuinfo is used min/max are set
  1640. # to None.
  1641. if LINUX and cpu.min is None:
  1642. set_none = True
  1643. continue
  1644. mins += cpu.min
  1645. maxs += cpu.max
  1646. current = currs / num_cpus
  1647. if set_none:
  1648. min_ = max_ = None
  1649. else:
  1650. min_ = mins / num_cpus
  1651. max_ = maxs / num_cpus
  1652. return _common.scpufreq(current, min_, max_)
  1653. __all__.append("cpu_freq")
  1654. if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"):
  1655. # Perform this hasattr check once on import time to either use the
  1656. # platform based code or proxy straight from the os module.
  1657. if hasattr(os, "getloadavg"):
  1658. getloadavg = os.getloadavg
  1659. else:
  1660. getloadavg = _psplatform.getloadavg
  1661. __all__.append("getloadavg")
  1662. # =====================================================================
  1663. # --- system memory related functions
  1664. # =====================================================================
  1665. def virtual_memory():
  1666. """Return statistics about system memory usage as a namedtuple
  1667. including the following fields, expressed in bytes:
  1668. - total:
  1669. total physical memory available.
  1670. - available:
  1671. the memory that can be given instantly to processes without the
  1672. system going into swap.
  1673. This is calculated by summing different memory values depending
  1674. on the platform and it is supposed to be used to monitor actual
  1675. memory usage in a cross platform fashion.
  1676. - percent:
  1677. the percentage usage calculated as (total - available) / total * 100
  1678. - used:
  1679. memory used, calculated differently depending on the platform and
  1680. designed for informational purposes only:
  1681. macOS: active + wired
  1682. BSD: active + wired + cached
  1683. Linux: total - free
  1684. - free:
  1685. memory not being used at all (zeroed) that is readily available;
  1686. note that this doesn't reflect the actual memory available
  1687. (use 'available' instead)
  1688. Platform-specific fields:
  1689. - active (UNIX):
  1690. memory currently in use or very recently used, and so it is in RAM.
  1691. - inactive (UNIX):
  1692. memory that is marked as not used.
  1693. - buffers (BSD, Linux):
  1694. cache for things like file system metadata.
  1695. - cached (BSD, macOS):
  1696. cache for various things.
  1697. - wired (macOS, BSD):
  1698. memory that is marked to always stay in RAM. It is never moved to disk.
  1699. - shared (BSD):
  1700. memory that may be simultaneously accessed by multiple processes.
  1701. The sum of 'used' and 'available' does not necessarily equal total.
  1702. On Windows 'available' and 'free' are the same.
  1703. """
  1704. global _TOTAL_PHYMEM
  1705. ret = _psplatform.virtual_memory()
  1706. # cached for later use in Process.memory_percent()
  1707. _TOTAL_PHYMEM = ret.total
  1708. return ret
  1709. def swap_memory():
  1710. """Return system swap memory statistics as a namedtuple including
  1711. the following fields:
  1712. - total: total swap memory in bytes
  1713. - used: used swap memory in bytes
  1714. - free: free swap memory in bytes
  1715. - percent: the percentage usage
  1716. - sin: no. of bytes the system has swapped in from disk (cumulative)
  1717. - sout: no. of bytes the system has swapped out from disk (cumulative)
  1718. 'sin' and 'sout' on Windows are meaningless and always set to 0.
  1719. """
  1720. return _psplatform.swap_memory()
  1721. # =====================================================================
  1722. # --- disks/paritions related functions
  1723. # =====================================================================
  1724. def disk_usage(path):
  1725. """Return disk usage statistics about the given *path* as a
  1726. namedtuple including total, used and free space expressed in bytes
  1727. plus the percentage usage.
  1728. """
  1729. return _psplatform.disk_usage(path)
  1730. def disk_partitions(all=False):
  1731. """Return mounted partitions as a list of
  1732. (device, mountpoint, fstype, opts) namedtuple.
  1733. 'opts' field is a raw string separated by commas indicating mount
  1734. options which may vary depending on the platform.
  1735. If *all* parameter is False return physical devices only and ignore
  1736. all others.
  1737. """
  1738. def pathconf(path, name):
  1739. try:
  1740. return os.pathconf(path, name)
  1741. except (OSError, AttributeError):
  1742. pass
  1743. ret = _psplatform.disk_partitions(all)
  1744. if POSIX:
  1745. new = []
  1746. for item in ret:
  1747. nt = item._replace(
  1748. maxfile=pathconf(item.mountpoint, 'PC_NAME_MAX'),
  1749. maxpath=pathconf(item.mountpoint, 'PC_PATH_MAX'))
  1750. new.append(nt)
  1751. return new
  1752. else:
  1753. return ret
  1754. def disk_io_counters(perdisk=False, nowrap=True):
  1755. """Return system disk I/O statistics as a namedtuple including
  1756. the following fields:
  1757. - read_count: number of reads
  1758. - write_count: number of writes
  1759. - read_bytes: number of bytes read
  1760. - write_bytes: number of bytes written
  1761. - read_time: time spent reading from disk (in ms)
  1762. - write_time: time spent writing to disk (in ms)
  1763. Platform specific:
  1764. - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
  1765. - read_merged_count (Linux): number of merged reads
  1766. - write_merged_count (Linux): number of merged writes
  1767. If *perdisk* is True return the same information for every
  1768. physical disk installed on the system as a dictionary
  1769. with partition names as the keys and the namedtuple
  1770. described above as the values.
  1771. If *nowrap* is True it detects and adjust the numbers which overflow
  1772. and wrap (restart from 0) and add "old value" to "new value" so that
  1773. the returned numbers will always be increasing or remain the same,
  1774. but never decrease.
  1775. "disk_io_counters.cache_clear()" can be used to invalidate the
  1776. cache.
  1777. On recent Windows versions 'diskperf -y' command may need to be
  1778. executed first otherwise this function won't find any disk.
  1779. """
  1780. kwargs = dict(perdisk=perdisk) if LINUX else {}
  1781. rawdict = _psplatform.disk_io_counters(**kwargs)
  1782. if not rawdict:
  1783. return {} if perdisk else None
  1784. if nowrap:
  1785. rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
  1786. nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
  1787. if perdisk:
  1788. for disk, fields in rawdict.items():
  1789. rawdict[disk] = nt(*fields)
  1790. return rawdict
  1791. else:
  1792. return nt(*(sum(x) for x in zip(*rawdict.values())))
  1793. disk_io_counters.cache_clear = functools.partial(
  1794. _wrap_numbers.cache_clear, 'psutil.disk_io_counters')
  1795. disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
  1796. # =====================================================================
  1797. # --- network related functions
  1798. # =====================================================================
  1799. def net_io_counters(pernic=False, nowrap=True):
  1800. """Return network I/O statistics as a namedtuple including
  1801. the following fields:
  1802. - bytes_sent: number of bytes sent
  1803. - bytes_recv: number of bytes received
  1804. - packets_sent: number of packets sent
  1805. - packets_recv: number of packets received
  1806. - errin: total number of errors while receiving
  1807. - errout: total number of errors while sending
  1808. - dropin: total number of incoming packets which were dropped
  1809. - dropout: total number of outgoing packets which were dropped
  1810. (always 0 on macOS and BSD)
  1811. If *pernic* is True return the same information for every
  1812. network interface installed on the system as a dictionary
  1813. with network interface names as the keys and the namedtuple
  1814. described above as the values.
  1815. If *nowrap* is True it detects and adjust the numbers which overflow
  1816. and wrap (restart from 0) and add "old value" to "new value" so that
  1817. the returned numbers will always be increasing or remain the same,
  1818. but never decrease.
  1819. "net_io_counters.cache_clear()" can be used to invalidate the
  1820. cache.
  1821. """
  1822. rawdict = _psplatform.net_io_counters()
  1823. if not rawdict:
  1824. return {} if pernic else None
  1825. if nowrap:
  1826. rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
  1827. if pernic:
  1828. for nic, fields in rawdict.items():
  1829. rawdict[nic] = _common.snetio(*fields)
  1830. return rawdict
  1831. else:
  1832. return _common.snetio(*[sum(x) for x in zip(*rawdict.values())])
  1833. net_io_counters.cache_clear = functools.partial(
  1834. _wrap_numbers.cache_clear, 'psutil.net_io_counters')
  1835. net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
  1836. def net_connections(kind='inet'):
  1837. """Return system-wide socket connections as a list of
  1838. (fd, family, type, laddr, raddr, status, pid) namedtuples.
  1839. In case of limited privileges 'fd' and 'pid' may be set to -1
  1840. and None respectively.
  1841. The *kind* parameter filters for connections that fit the
  1842. following criteria:
  1843. +------------+----------------------------------------------------+
  1844. | Kind Value | Connections using |
  1845. +------------+----------------------------------------------------+
  1846. | inet | IPv4 and IPv6 |
  1847. | inet4 | IPv4 |
  1848. | inet6 | IPv6 |
  1849. | tcp | TCP |
  1850. | tcp4 | TCP over IPv4 |
  1851. | tcp6 | TCP over IPv6 |
  1852. | udp | UDP |
  1853. | udp4 | UDP over IPv4 |
  1854. | udp6 | UDP over IPv6 |
  1855. | unix | UNIX socket (both UDP and TCP protocols) |
  1856. | all | the sum of all the possible families and protocols |
  1857. +------------+----------------------------------------------------+
  1858. On macOS this function requires root privileges.
  1859. """
  1860. return _psplatform.net_connections(kind)
  1861. def net_if_addrs():
  1862. """Return the addresses associated to each NIC (network interface
  1863. card) installed on the system as a dictionary whose keys are the
  1864. NIC names and value is a list of namedtuples for each address
  1865. assigned to the NIC. Each namedtuple includes 5 fields:
  1866. - family: can be either socket.AF_INET, socket.AF_INET6 or
  1867. psutil.AF_LINK, which refers to a MAC address.
  1868. - address: is the primary address and it is always set.
  1869. - netmask: and 'broadcast' and 'ptp' may be None.
  1870. - ptp: stands for "point to point" and references the
  1871. destination address on a point to point interface
  1872. (typically a VPN).
  1873. - broadcast: and *ptp* are mutually exclusive.
  1874. Note: you can have more than one address of the same family
  1875. associated with each interface.
  1876. """
  1877. has_enums = _PY3
  1878. if has_enums:
  1879. import socket
  1880. rawlist = _psplatform.net_if_addrs()
  1881. rawlist.sort(key=lambda x: x[1]) # sort by family
  1882. ret = collections.defaultdict(list)
  1883. for name, fam, addr, mask, broadcast, ptp in rawlist:
  1884. if has_enums:
  1885. try:
  1886. fam = socket.AddressFamily(fam)
  1887. except ValueError:
  1888. if WINDOWS and fam == -1:
  1889. fam = _psplatform.AF_LINK
  1890. elif (hasattr(_psplatform, "AF_LINK") and
  1891. fam == _psplatform.AF_LINK):
  1892. # Linux defines AF_LINK as an alias for AF_PACKET.
  1893. # We re-set the family here so that repr(family)
  1894. # will show AF_LINK rather than AF_PACKET
  1895. fam = _psplatform.AF_LINK
  1896. if fam == _psplatform.AF_LINK:
  1897. # The underlying C function may return an incomplete MAC
  1898. # address in which case we fill it with null bytes, see:
  1899. # https://github.com/giampaolo/psutil/issues/786
  1900. separator = ":" if POSIX else "-"
  1901. while addr.count(separator) < 5:
  1902. addr += "%s00" % separator
  1903. ret[name].append(_common.snicaddr(fam, addr, mask, broadcast, ptp))
  1904. return dict(ret)
  1905. def net_if_stats():
  1906. """Return information about each NIC (network interface card)
  1907. installed on the system as a dictionary whose keys are the
  1908. NIC names and value is a namedtuple with the following fields:
  1909. - isup: whether the interface is up (bool)
  1910. - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
  1911. NIC_DUPLEX_UNKNOWN
  1912. - speed: the NIC speed expressed in mega bits (MB); if it can't
  1913. be determined (e.g. 'localhost') it will be set to 0.
  1914. - mtu: the maximum transmission unit expressed in bytes.
  1915. """
  1916. return _psplatform.net_if_stats()
  1917. # =====================================================================
  1918. # --- sensors
  1919. # =====================================================================
  1920. # Linux, macOS
  1921. if hasattr(_psplatform, "sensors_temperatures"):
  1922. def sensors_temperatures(fahrenheit=False):
  1923. """Return hardware temperatures. Each entry is a namedtuple
  1924. representing a certain hardware sensor (it may be a CPU, an
  1925. hard disk or something else, depending on the OS and its
  1926. configuration).
  1927. All temperatures are expressed in celsius unless *fahrenheit*
  1928. is set to True.
  1929. """
  1930. def convert(n):
  1931. if n is not None:
  1932. return (float(n) * 9 / 5) + 32 if fahrenheit else n
  1933. ret = collections.defaultdict(list)
  1934. rawdict = _psplatform.sensors_temperatures()
  1935. for name, values in rawdict.items():
  1936. while values:
  1937. label, current, high, critical = values.pop(0)
  1938. current = convert(current)
  1939. high = convert(high)
  1940. critical = convert(critical)
  1941. if high and not critical:
  1942. critical = high
  1943. elif critical and not high:
  1944. high = critical
  1945. ret[name].append(
  1946. _common.shwtemp(label, current, high, critical))
  1947. return dict(ret)
  1948. __all__.append("sensors_temperatures")
  1949. # Linux
  1950. if hasattr(_psplatform, "sensors_fans"):
  1951. def sensors_fans():
  1952. """Return fans speed. Each entry is a namedtuple
  1953. representing a certain hardware sensor.
  1954. All speed are expressed in RPM (rounds per minute).
  1955. """
  1956. return _psplatform.sensors_fans()
  1957. __all__.append("sensors_fans")
  1958. # Linux, Windows, FreeBSD, macOS
  1959. if hasattr(_psplatform, "sensors_battery"):
  1960. def sensors_battery():
  1961. """Return battery information. If no battery is installed
  1962. returns None.
  1963. - percent: battery power left as a percentage.
  1964. - secsleft: a rough approximation of how many seconds are left
  1965. before the battery runs out of power. May be
  1966. POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
  1967. - power_plugged: True if the AC power cable is connected.
  1968. """
  1969. return _psplatform.sensors_battery()
  1970. __all__.append("sensors_battery")
  1971. # =====================================================================
  1972. # --- other system related functions
  1973. # =====================================================================
  1974. def boot_time():
  1975. """Return the system boot time expressed in seconds since the epoch."""
  1976. # Note: we are not caching this because it is subject to
  1977. # system clock updates.
  1978. return _psplatform.boot_time()
  1979. def users():
  1980. """Return users currently connected on the system as a list of
  1981. namedtuples including the following fields.
  1982. - user: the name of the user
  1983. - terminal: the tty or pseudo-tty associated with the user, if any.
  1984. - host: the host name associated with the entry, if any.
  1985. - started: the creation time as a floating point number expressed in
  1986. seconds since the epoch.
  1987. """
  1988. return _psplatform.users()
  1989. # =====================================================================
  1990. # --- Windows services
  1991. # =====================================================================
  1992. if WINDOWS:
  1993. def win_service_iter():
  1994. """Return a generator yielding a WindowsService instance for all
  1995. Windows services installed.
  1996. """
  1997. return _psplatform.win_service_iter()
  1998. def win_service_get(name):
  1999. """Get a Windows service by *name*.
  2000. Raise NoSuchProcess if no service with such name exists.
  2001. """
  2002. return _psplatform.win_service_get(name)
  2003. # =====================================================================
  2004. def _set_debug(value):
  2005. """Enable or disable PSUTIL_DEBUG option, which prints debugging
  2006. messages to stderr.
  2007. """
  2008. import psutil._common
  2009. psutil._common.PSUTIL_DEBUG = bool(value)
  2010. _psplatform.cext.set_debug(bool(value))
  2011. def test(): # pragma: no cover
  2012. from ._common import bytes2human
  2013. from ._compat import get_terminal_size
  2014. today_day = datetime.date.today()
  2015. templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s"
  2016. attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
  2017. 'create_time', 'memory_info', 'status', 'nice', 'username']
  2018. print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE", # NOQA
  2019. "STATUS", "START", "TIME", "CMDLINE"))
  2020. for p in process_iter(attrs, ad_value=None):
  2021. if p.info['create_time']:
  2022. ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
  2023. if ctime.date() == today_day:
  2024. ctime = ctime.strftime("%H:%M")
  2025. else:
  2026. ctime = ctime.strftime("%b%d")
  2027. else:
  2028. ctime = ''
  2029. if p.info['cpu_times']:
  2030. cputime = time.strftime("%M:%S",
  2031. time.localtime(sum(p.info['cpu_times'])))
  2032. else:
  2033. cputime = ''
  2034. user = p.info['username'] or ''
  2035. if not user and POSIX:
  2036. try:
  2037. user = p.uids()[0]
  2038. except Error:
  2039. pass
  2040. if user and WINDOWS and '\\' in user:
  2041. user = user.split('\\')[1]
  2042. user = user[:9]
  2043. vms = bytes2human(p.info['memory_info'].vms) if \
  2044. p.info['memory_info'] is not None else ''
  2045. rss = bytes2human(p.info['memory_info'].rss) if \
  2046. p.info['memory_info'] is not None else ''
  2047. memp = round(p.info['memory_percent'], 1) if \
  2048. p.info['memory_percent'] is not None else ''
  2049. nice = int(p.info['nice']) if p.info['nice'] else ''
  2050. if p.info['cmdline']:
  2051. cmdline = ' '.join(p.info['cmdline'])
  2052. else:
  2053. cmdline = p.info['name']
  2054. status = p.info['status'][:5] if p.info['status'] else ''
  2055. line = templ % (
  2056. user[:10],
  2057. p.info['pid'],
  2058. memp,
  2059. vms,
  2060. rss,
  2061. nice,
  2062. status,
  2063. ctime,
  2064. cputime,
  2065. cmdline)
  2066. print(line[:get_terminal_size()[0]]) # NOQA
  2067. del memoize_when_activated, division
  2068. if sys.version_info[0] < 3:
  2069. del num, x # noqa
  2070. if __name__ == "__main__":
  2071. test()