__init__.py 84 KB

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