a MÝ_ÝRã@sjdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z z ddl Z Wney‚dZ Yn0ddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-dd lm.Z.dd!lm/Z/dd"lm0Z0dd#lm1Z1dd$lm2Z2dd%lm3Z3dd&lm4Z4dd'lm5Z5dd(lm6Z6dd)lm7Z7dd*lm8Z8dd+lm9Z9dd,lm:Z:dd-lm;Z;dd.lmZ>dd1lm?Z?dd2lm@Z@dd3lmAZAdd4lmBZBdd5lmCZCdd6lmDZDdd7lmEZEdd8lmFZFe?r>d9ZGdd:lmHZIdd;lHmJZJddlHmMZMneFrÖdd?lmNZIdd@lOmPZPddAlOmQZQddBlOmRZRddClOmSZSddDlOmTZTddElOmUZUddFlNmVZVddGlNmWZWddHlNmXZXddIlNmYZYddJlNmZZZn~e@rêddKlm[ZInje=rþddLlm\ZInVeEr.ddMlm]ZIddNl]m^Z^ddOl]m_Z_d9ZGn&e<rFddPlm`ZId9ZGneadQe jbƒ‚gdR¢Zcec deIje¡efeIjgdSƒrÎddTlmhZheiƒZjdZkelehƒD]4Zkek mdU¡r”ek n¡r”eoehekƒejek<ec pek¡q”[j[keIjqZqdVZrdWZsetdXdY„es udZ¡DƒƒZveoe d[e j ƒZwdaxdayezƒZ{e|es }dZd\¡ƒeoeIj~d]dƒkrªd^eoeIj~d_ƒZefeIj~d]ƒrxed`dZ €dadY„eeIj~j‚ƒDƒ¡esf7Zn edbes7ZedceoeIj~d_ddƒ7Zede7Zeeƒ‚efeIdfƒr¾eIjƒZ„ndgdh„Z„didj„Z…dkdl„Z†Gdmdn„dnezƒZge‡dodY„elegƒDƒƒZˆGdpdq„dqegƒZ‰drds„ZŠdtdu„Z‹iZŒe  ¡ZŽd¸dvdw„Zd¹dxdy„Zdºd{d|„Z‘d»d~d„Z’z e’ƒa“Wne”yrda“Yn0ze’dzd€a•Wne”yšda•Yn0dd‚„Z–dƒd„„Z—d…d†„Z˜d¼d‡dˆ„Z™t“ašt•a›d½d‰dŠ„Zœd‹dŒ„ZefeIdƒrød¾dŽd„Zžec pd¡efedƒsefeIdƒr4efedƒr$ejŸZŸneIjŸZŸec pd¡dd‘„Z d’d“„Z¡d”d•„Z¢d¿d–d—„Z£dÀd˜d™„Z¤e ¥ej¦dš¡e¤_¦d›e¤j¦_dÁdœd„Z§e ¥ej¦dž¡e§_¦d›e§j¦_dÂd d¡„Z¨d¢d£„Z©d¤d¥„ZªefeId¦ƒrÔdÃd§d¦„Z«ec pd¦¡efeId¨ƒròd©d¨„Z¬ec pd¨¡efeIdªƒrd«dª„Z­ec pdª¡d¬d­„Z®d®d¯„Z¯eFr6d°d±„Z°d²d³„Z±d´dµ„Z²[[e jvdd¶krV[³[´eµd·krfe²ƒdS)Äa3psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. Supported platforms: - Linux - Windows - macOS - FreeBSD - OpenBSD - NetBSD - Sun Solaris - AIX Works with Python versions from 2.6 to 3.4+. é)ÚdivisionNé)Ú_common)Ú AccessDenied)ÚError)Úmemoize_when_activated)Ú NoSuchProcess)ÚTimeoutExpired)Ú wrap_numbers)Ú ZombieProcess)Úlong)ÚPermissionError)ÚProcessLookupError)ÚPY3)Ú CONN_CLOSE)ÚCONN_CLOSE_WAIT)Ú CONN_CLOSING)ÚCONN_ESTABLISHED)ÚCONN_FIN_WAIT1)ÚCONN_FIN_WAIT2)Ú CONN_LAST_ACK)Ú CONN_LISTEN)Ú CONN_NONE)Ú CONN_SYN_RECV)Ú CONN_SYN_SENT)ÚCONN_TIME_WAIT)ÚNIC_DUPLEX_FULL)ÚNIC_DUPLEX_HALF)ÚNIC_DUPLEX_UNKNOWN)ÚPOWER_TIME_UNKNOWN)ÚPOWER_TIME_UNLIMITED)Ú STATUS_DEAD)ÚSTATUS_DISK_SLEEP)Ú STATUS_IDLE)Ú STATUS_LOCKED)Ú STATUS_PARKED)ÚSTATUS_RUNNING)ÚSTATUS_SLEEPING)ÚSTATUS_STOPPED)ÚSTATUS_TRACING_STOP)ÚSTATUS_WAITING)Ú STATUS_WAKING)Ú STATUS_ZOMBIE)ÚAIX)ÚBSD)ÚFREEBSD)ÚLINUX)ÚMACOS)ÚNETBSD)ÚOPENBSD)ÚOSX)ÚPOSIX)ÚSUNOS)ÚWINDOWSz/proc)Ú_pslinux)ÚIOPRIO_CLASS_BE)ÚIOPRIO_CLASS_IDLE)ÚIOPRIO_CLASS_NONE)ÚIOPRIO_CLASS_RT)Ú _pswindows)ÚABOVE_NORMAL_PRIORITY_CLASS)ÚBELOW_NORMAL_PRIORITY_CLASS)ÚHIGH_PRIORITY_CLASS)ÚIDLE_PRIORITY_CLASS)ÚNORMAL_PRIORITY_CLASS)ÚREALTIME_PRIORITY_CLASS)ÚCONN_DELETE_TCB)ÚIOPRIO_VERYLOW)Ú IOPRIO_LOW)Ú IOPRIO_NORMAL)Ú IOPRIO_HIGH)Ú_psosx)Ú_psbsd)Ú_pssunos)Ú CONN_BOUND)Ú CONN_IDLE)Ú_psaixzplatform %s is not supported)Grrr rr Ú version_infoÚ __version__r&r#r'r"r(r)r,r!r+r$r*r$r%rrrrrrrrrrrrÚAF_LINKrrrrr r.r/r0r2r3r1r4r5r6r7r-ÚProcessÚPopenÚ pid_existsÚpidsÚ process_iterÚ wait_procsÚvirtual_memoryÚ swap_memoryÚ cpu_timesÚ cpu_percentÚcpu_times_percentÚ cpu_countÚ cpu_statsÚnet_io_countersÚnet_connectionsÚ net_if_addrsÚ net_if_statsÚdisk_io_countersÚdisk_partitionsÚ disk_usageÚusersÚ boot_timeÚrlimit)Ú _psutil_posixZRLIMzGiampaolo Rodola'z5.8.0cCsg|] }t|ƒ‘qS©)Úint)Ú.0Únumrjrjú5/usr/lib64/python3.9/site-packages/psutil/__init__.pyÚ ÕóroÚ.Ú monotonicÚÚversionzOversion conflict: %r C extension module was built for another version of psutilÚ__file__z (%s instead of %s)cCsg|]}|‘qSrjrj©rlÚxrjrjrnroèrpz (different than %s)z;; you may try to 'pip uninstall psutil', manually remove %sz%the existing psutil install directoryz1 or clean the virtual env somehow, then reinstallÚppid_mapc CsBi}tƒD]2}zt |¡ ¡||<Wq ttfy:Yq 0q |S)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )rUÚ _psplatformrRÚppidrr )ÚretÚpidrjrjrnÚ _ppid_mapûs r}cst ˆ¡‡fdd„ƒ}|S)zpDecorator which raises NoSuchProcess in case a process is no longer running or its PID has been reused. cs,| ¡st|j|jƒ‚ˆ|g|¢Ri|¤ŽS©N)Ú is_runningrr|Ú_name©ÚselfÚargsÚkwargs©ÚfunrjrnÚwrapper sz'_assert_pid_not_reused..wrapper)Ú functoolsÚwraps)r†r‡rjr…rnÚ_assert_pid_not_reusedsrŠcCs8t ¡}t||ƒ}|dkr"d}nd}tj |¡ |¡S)z(Format seconds in a human readable form.i€Qz%H:%M:%Sz%Y-%m-%d %H:%M:%S)ÚtimerkÚdatetimeÚ fromtimestampÚstrftime)ZsecsZnowZsecs_agoZfmtrjrjrnÚ _pprint_secss  rc@sŽeZdZdZdydd„Zdzdd„Zdd „ZeZd d „Zd d „Z dd„Z e dd„ƒZ e jdd„ƒZd{dd„Zdd„Zdd„Zdd„Zedd„ƒZdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zd|d,d-„Zerøed.d/„ƒZd0d1„Z d2d3„Z!d4d5„Z"e#e$j%d6ƒrd7d8„Z&e#e$j%d9ƒr&d}d:d;„Z'e#e$j%d<ƒr>d~d=d>„Z(e#e$j%d?ƒrVdd@dA„Z)e#e$j%dBƒrldCdD„Z*e#e$j%dEƒr‚dFdG„Z+e,rdHdI„Z-dJdK„Z.dLdM„Z/e#e$j%dNƒr¶dOdP„Z0e1d€dQdR„ƒZ2ddSdT„Z3edUdV„ƒZ4edWdX„ƒZ5e6j7dYdZd[d\„ƒZ8d]d^„Z9d‚d`da„Z:e#e$j%dbƒr$dƒddde„Z;dfdg„Ze1dmdn„ƒZ?e1dodp„ƒZ@e1dqdr„ƒZAe1dsdt„ƒZBe1dudv„ƒZCd…dwdx„ZDdS)†rRa'Represents an OS process with the given PID. If PID is omitted current process PID (os.getpid()) is used. Raise NoSuchProcess if PID does not exist. Note that most of the methods of this class do not make sure the PID of the process being queried has been reused over time. That means you might end up retrieving an information referring to another process in case the original one this instance refers to is gone in the meantime. The only exceptions for which process identity is pre-emptively checked and guaranteed are: - parent() - children() - nice() (set) - ionice() (set) - rlimit() (set) - cpu_affinity (set) - suspend() - resume() - send_signal() - terminate() - kill() To prevent this problem for all other methods you can: - use is_running() before querying the process - if you're continuously iterating over a set of Process instances use process_iter() which pre-emptively checks process identity for every yielded instance NcCs| |¡dSr~)Ú_init)r‚r|rjrjrnÚ__init__EszProcess.__init__FcCs|durt ¡}n2ts0t|ttfƒs0td|ƒ‚|dkrDtd|ƒ‚||_d|_ d|_ d|_ d|_ d|_ t ¡|_d|_t |¡|_d|_d|_t|_z | ¡WnRty´YnBtyÄYn2tyô|sêd|}t|d|ƒ‚nd|_ Yn0|j|j f|_dS)Nzpid must be an integer (got %r)rz'pid must be a positive integer (got %s)Fzno process found with pid %sT)ÚosÚgetpidÚ_PY3Ú isinstancerkr Ú TypeErrorÚ ValueErrorÚ_pidr€Ú_exeÚ _create_timeÚ_goneÚ_hashÚ threadingÚRLockÚ_lockÚ_ppidryrRÚ_procÚ_last_sys_cpu_timesÚ_last_proc_cpu_timesÚ _SENTINELÚ _exitcodeÚ create_timerr rr|Ú_ident)r‚r|Ú _ignore_nspÚmsgrjrjrnrHs@  ÿ       z Process._initc Cs"z t ¡}Wnty"i}Yn0|j|d<|jr>|j|d<| ¡Æz| ¡|d<| ¡|d<WnBty~d|d<Yn*t y–d|d<Ynt y¦Yn0|j t dfvrÀ|j |d<|j rÔt|j ƒ|d<d|jj|jjd  d d „| ¡Dƒ¡fWdƒS1s0YdS) Nr|ÚnameÚstatusZzombieZ terminatedZexitcodeÚstartedz %s.%s(%s)ú, cSsg|]\}}d||f‘qS)z%s=%rrj)rlÚkÚvrjrjrnro‘rpz#Process.__str__..)Ú collectionsÚ OrderedDictÚAttributeErrorr|r€Úoneshotrªr«r rrr¥r¤ršrÚ __class__Ú __module__Ú__name__ÚjoinÚitems)r‚ÚinforjrjrnÚ__str__xs4             ýzProcess.__str__cCst|tƒstS|j|jkSr~)r•rRÚNotImplementedr§©r‚ÚotherrjrjrnÚ__eq__•s zProcess.__eq__cCs ||k Sr~rjr¼rjrjrnÚ__ne__œszProcess.__ne__cCs|jdurt|jƒ|_|jSr~)rœÚhashr§©r‚rjrjrnÚ__hash__Ÿs  zProcess.__hash__cCs|jS)zThe process PID.)r˜rÁrjrjrnr|¤sz Process.pidc cs|jêt|dƒrdVnÈz†|j |¡|j |¡|j |¡trP|j |¡|j  ¡dVW|j  |¡|j  |¡|j  |¡tr–|j  |¡|j  ¡n@|j  |¡|j  |¡|j  |¡trÖ|j  |¡|j  ¡0Wdƒn1sö0YdS)a#Utility context manager which considerably speeds up the retrieval of multiple process information at the same time. Internally different process info (e.g. name, ppid, uids, gids, ...) may be fetched by using the same routine, but only one information is returned and the others are discarded. When using this context manager the internal routine is executed once (in the example below on name()) and the other info are cached. The cache is cleared when exiting the context manager block. The advice is to use this every time you retrieve more than one information about the process. If you're lucky, you'll get a hell of a speedup. >>> import psutil >>> p = psutil.Process() >>> with p.oneshot(): ... p.name() # collect multiple info ... p.cpu_times() # return cached value ... p.cpu_percent() # return cached value ... p.create_time() # return cached value ... >>> Ú_cacheN) rŸÚhasattrrZZcache_activateÚ memory_inforzr5Úuidsr¡Z oneshot_enterZcache_deactivateZ oneshot_exitrÁrjrjrnr³«s.           û    zProcess.oneshotc Cst}|durnt|ttttfƒs.tdt|ƒƒ‚t|ƒ}||}|rntdt |ƒdkrVdndd  t t |ƒ¡fƒ‚t ƒ}|pz|}| ¡||D]f}z$|dkr |j}nt||ƒ} | ƒ}Wn4ttfyÌ|}Yntyæ|rÞ‚YqŠYn0|||<qŠWdƒn1s0Y|S) aäUtility method returning process information as a hashable dictionary. If *attrs* is specified it must be a list of strings reflecting available Process class' attribute names (e.g. ['cpu_times', 'name']) else all public (read only) attributes are assumed. *ad_value* is the value which gets assigned in case AccessDenied or ZombieProcess exception is raised when retrieving that particular process information. Nzinvalid attrs type %szinvalid attr name%s %srÚsrsr­r|)Ú_as_dict_attrnamesr•ÚlistÚtupleÚsetÚ frozensetr–Útyper—Úlenr·ÚmapÚreprÚdictr³r|Úgetattrrr ÚNotImplementedError) r‚ÚattrsÚad_valueZ valid_namesÚ invalid_namesZretdictÚlsrªr{ÚmethrjrjrnÚas_dictîs8 þ     *zProcess.as_dictcCsrtdur tntƒd}|j|kr$dS| ¡}|durn| ¡}zt|ƒ}| ¡|krX|WSWntylYn0dS)zReturn the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None. Nr)Ú _LOWEST_PIDrUr|rzr¦rRr)r‚Z lowest_pidrzÚctimeÚparentrjrjrnrÜs    zProcess.parentcCs,g}| ¡}|dur(| |¡| ¡}q |S)zReturn the parents of this process as a list of Process instances. If no parents are known return an empty list. N)rÜÚappend)r‚ÚparentsÚprocrjrjrnrÞ-s   zProcess.parentscCsL|jr dSz|t|jƒkWSty.YdStyFd|_YdS0dS)z•Return whether this process is running. It also checks if PID has been reused by another process in which case return False. FTN)r›rRr|r rrÁrjrjrnr8s  zProcess.is_runningcCs*tr|j ¡S|jp|j ¡|_|jSdS)z`The process parent PID. On Windows the return value is cached after first call. N)r5r¡rzr rÁrjrjrnrzPs  z Process.ppidcCs‚tr|jdur|jS|j ¡}trpt|ƒdkrpz | ¡}WntyLYn$0|rptj   |d¡}|  |¡rp|}||_||j_|S)z>The process name. The return value is cached after first call.Nér) r7r€r¡rªr5rÎÚcmdlinerr’ÚpathÚbasenameÚ startswith)r‚rªráZ extended_namerjrjrnrªbs    z Process.namec s†‡fdd„}ˆjdur€zˆj ¡}Wn.tyR}z||dWYd}~Sd}~00|szz||d}WntyxYn0|ˆ_ˆjS)zŽThe process executable as an absolute path. May also be an empty string. The return value is cached after first call. csdˆ ¡}|rRttdƒrRttdƒrR|d}tj |¡rRtj |¡rRt |tj¡rR|St|t ƒr`|‚|S)NÚaccessÚX_OKr) rárÄr’râÚisabsÚisfilerårær•r)ÚfallbackráÚexerÁrjrnÚguess_its  ÿ þ zProcess.exe..guess_itN)ré)r™r¡rêr)r‚rërêÚerrrjrÁrnrê|s    z Process.execCs |j ¡S)z3The command line this process has been called with.)r¡rárÁrjrjrnrá£szProcess.cmdlinecCs(z |j ¡WSty"tYS0dS)z2The process current status as a STATUS_* constant.N)r¡r«r r,rÁrjrjrnr«§s  zProcess.statuscCsXtrJtdurtdƒ‚| ¡j}zt |¡jWStyFt|ƒYS0n |j   ¡SdS)ztThe name of the user that owns the process. On UNIX this is calculated by using *real* process uid. Nz0requires pwd module shipped with standard python) r5ÚpwdÚ ImportErrorrÆÚrealÚgetpwuidÚpw_nameÚKeyErrorÚstrr¡Úusername)r‚Zreal_uidrjrjrnrô®sÿ  zProcess.usernamecCs|jdur|j ¡|_|jS)z The process creation time as a floating point number expressed in seconds since the epoch. The return value is cached after first call. N)ršr¡r¦rÁrjrjrnr¦Às  zProcess.create_timecCs |j ¡S)z6Process current working directory as an absolute path.)r¡ÚcwdrÁrjrjrnrõÉsz Process.cwdcCs8|dur|j ¡S| ¡s(t|j|jƒ‚|j |¡dS)z'Get or set process niceness (priority).N)r¡Znice_getrrr|r€Znice_set)r‚ÚvaluerjrjrnÚniceÍs  z Process.nicecCs |j ¡S)zVReturn process UIDs as a (real, effective, saved) namedtuple. )r¡rÆrÁrjrjrnrÆØsz Process.uidscCs |j ¡S)zVReturn process GIDs as a (real, effective, saved) namedtuple. )r¡ÚgidsrÁrjrjrnrøßsz Process.gidscCs |j ¡S)zVThe terminal associated with this process, if any, else None. )r¡ÚterminalrÁrjrjrnrùåszProcess.terminalcCs |j ¡S)zcReturn the number of file descriptors opened by this process (POSIX only). )r¡Únum_fdsrÁrjrjrnrúëszProcess.num_fdsÚ io_counterscCs |j ¡S)a Return process I/O statistics as a (read_count, write_count, read_bytes, write_bytes) namedtuple. Those are the number of read/write calls performed and the amount of bytes read and written by the process. )r¡rûrÁrjrjrnrûôszProcess.io_countersÚ ionice_getcCs4|dur"|durtdƒ‚|j ¡S|j ||¡SdS)a´Get or set process I/O niceness (priority). On Linux *ioclass* is one of the IOPRIO_CLASS_* constants. *value* is a number which goes from 0 to 7. The higher the value, the lower the I/O priority of the process. On Windows only *ioclass* is used and it can be set to 2 (normal), 1 (low) or 0 (very low). Available on Linux and Windows > Vista only. Nz$'ioclass' argument must be specified)r—r¡rüZ ionice_set)r‚ZioclassrörjrjrnÚionices  zProcess.ionicerhcCs|j ||¡S)a-Get or set process resource limits as a (soft, hard) tuple. *resource* is one of the RLIMIT_* constants. *limits* is supposed to be a (soft, hard) tuple. See "man prlimit" for further info. Available on Linux and FreeBSD only. )r¡rh)r‚ÚresourceZlimitsrjrjrnrhs zProcess.rlimitÚcpu_affinity_getcCsd|durtt|j ¡ƒƒS|sLt|jdƒr6|j ¡}ntttt ddƒƒƒ}|j  t t|ƒƒ¡dS)a-Get or set process CPU affinity. If specified, *cpus* must be a list of CPUs for which you want to set the affinity (e.g. [0, 1]). If an empty list is passed, all egible CPUs are assumed (and set). (Windows, Linux and BSD only). NÚ_get_eligible_cpusT©Úpercpu) ÚsortedrËr¡rÿrÄrrÊÚrangerÎrZZcpu_affinity_setrÉ)r‚ZcpusrjrjrnÚ cpu_affinity%s  zProcess.cpu_affinityÚcpu_numcCs |j ¡S)aZReturn what CPU this process is currently running on. The returned number should be <= psutil.cpu_count() and <= len(psutil.cpu_percent(percpu=True)). It may be used in conjunction with psutil.cpu_percent(percpu=True) to observe the system workload distributed across CPUs. )r¡rrÁrjrjrnr:szProcess.cpu_numÚenvironcCs |j ¡S)z‡The environment variables of the process as a dict. Note: this might not reflect changes made after the process started. )r¡rrÁrjrjrnrGszProcess.environcCs |j ¡S)z\Return the number of handles opened by this process (Windows only). )r¡Ú num_handlesrÁrjrjrnrNszProcess.num_handlescCs |j ¡S)zkReturn the number of voluntary and involuntary context switches performed by this process. )r¡Únum_ctx_switchesrÁrjrjrnr TszProcess.num_ctx_switchescCs |j ¡S)z2Return the number of threads used by this process.)r¡Ú num_threadsrÁrjrjrnr ZszProcess.num_threadsÚthreadscCs |j ¡S)zïReturn threads opened by process as a list of (id, user_time, system_time) namedtuples representing thread id and thread CPU times (user/system). On OpenBSD this method requires root access. )r¡r rÁrjrjrnr `szProcess.threadsc Cs(tƒ}g}|sj| ¡D]P\}}||jkrz&t|ƒ}| ¡| ¡krL| |¡WqttfydYq0qnºt  t ¡}| ¡D]\}}|| |¡q|t ƒ}|jg} | r$|   ¡}||vrºq¢|  |¡||D]T} z6t| ƒ}| ¡| ¡k} | r| |¡|  | ¡WqÌttfyYqÌ0qÌq¢|S)u(Return the children of this process as a list of Process instances, pre-emptively checking whether PID has been reused. If *recursive* is True return all the parent descendants. Example (A == this process): A ─┠│ ├─ B (child) ─┠│ └─ X (grandchild) ─┠│ └─ Y (great grandchild) ├─ C (child) └─ D (child) >>> import psutil >>> p = psutil.Process() >>> p.children() B, C, D >>> p.children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be listed as the reference to process A is lost. )r}r¸r|rRr¦rÝrr r°Ú defaultdictrÉrËÚpopÚadd) r‚Ú recursiverxr{r|rzÚchildZreverse_ppid_mapÚseenÚstackZ child_pidZintimerjrjrnÚchildrenhs>       zProcess.childrenc s|duo|dk}|dur,|dkr,td|ƒ‚tƒp4d‰‡fdd„}|rr|ƒ}|j ¡}t |¡|ƒ}|j ¡}n<|j}|j}|ƒ}|j ¡}|dusž|dur®||_||_dS|j|j|j |j }||} ||_||_z|| d} Wnt yYdS0| ˆ} t | dƒSdS) aReturn a float representing the current process CPU utilization as a percentage. When *interval* is 0.0 or None (default) compares process times to system CPU times elapsed since last call, returning immediately (non-blocking). That means that the first time this is called it will return a meaningful 0.0 value. When *interval* is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. A value > 100.0 can be returned in case of processes running multiple threads on different CPU cores. The returned value is explicitly NOT split evenly between all available logical CPUs. This means that a busy loop process running on a system with 2 logical CPUs will be reported as having 100% CPU utilization instead of 50%. Examples: >>> import psutil >>> p = psutil.Process(os.getpid()) >>> # blocking >>> p.cpu_percent(interval=1) 2.0 >>> # non-blocking (percentage since last call) >>> p.cpu_percent(interval=None) 2.9 >>> Nçrú!interval is not positive (got %r)rcs tƒˆSr~)Ú_timerrj©Únum_cpusrjrnÚtimerÖsz"Process.cpu_percent..timeréd) r—r]r¡rZr‹Úsleepr¢r£ÚuserÚsystemÚZeroDivisionErrorÚround) r‚ÚintervalÚblockingrZst1Zpt1Zst2Zpt2Z delta_procZ delta_timeZoverall_cpus_percentZsingle_cpu_percentrjrrnr[®s:#       zProcess.cpu_percentcCs |j ¡S)a%Return a (user, system, children_user, children_system) namedtuple representing the accumulated process time, in seconds. This is similar to os.times() but per-process. On macOS and Windows children_user and children_system are always set to 0. )r¡rZrÁrjrjrnrZ s zProcess.cpu_timescCs |j ¡S)aReturn a namedtuple with variable fields depending on the platform, representing memory information about the process. The "portable" fields available on all plaforms are `rss` and `vms`. All numbers are expressed in bytes. )r¡rÅrÁrjrjrnrÅs zProcess.memory_inforÅ)Z replacementcCs| ¡Sr~)rÅrÁrjrjrnÚmemory_info_ex szProcess.memory_info_excCs |j ¡S)a]This method returns the same information as memory_info(), plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of actual process memory usage. Namely USS is the memory which is unique to a process and which would be freed if the process was terminated right now. It does so by passing through the whole process address. As such it usually requires higher user privileges than memory_info() and is considerably slower. )r¡Úmemory_full_inforÁrjrjrnr#$szProcess.memory_full_infoÚrsscCs€ttjjƒ}||vr(td|t|ƒfƒ‚|tjjvr:|jn|j}|ƒ}t ||ƒ}t pZt ƒj }|dksptd|ƒ‚|t |ƒdS)aÏCompare process memory to total physical system memory and calculate process memory utilization as a percentage. *memtype* argument is a string that dictates what type of process memory you want to compare against (defaults to "rss"). The list of available strings can be obtained like this: >>> psutil.Process().memory_info()._fields ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss') z&invalid memtype %r; valid types are %rrz`can't calculate process memory percent because total physical system memory is not positive (%r)r)rÉryZpfullmemÚ_fieldsr—rÊZpmemrÅr#rÒÚ _TOTAL_PHYMEMrXÚtotalÚfloat)r‚ZmemtypeZ valid_typesr†ZmetricsröZ total_phymemrjrjrnÚmemory_percent4s$ ÿÿ  þÿzProcess.memory_percentÚ memory_mapsTc sž|j ¡}|r‚i‰|D]P}|d}|dd…}ztdd„ˆ||ƒˆ|<Wqtyd|ˆ|<Yq0qtj‰‡‡fdd„ˆDƒStj‰‡fdd„|DƒSdS) aüReturn process' mapped memory regions as a list of namedtuples whose fields are variable depending on the platform. If *grouped* is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If *grouped* is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). ééNcSs||Sr~rj)rwÚyrjrjrnÚdrpz%Process.memory_maps..cs g|]}ˆ|gˆ|¢RŽ‘qSrjrj)rlrâ©ÚdÚntrjrnrohrpz'Process.memory_maps..csg|] }ˆ|Ž‘qSrjrjrv)r1rjrnrokrp)r¡r*rÏròryZ pmmap_groupedZ pmmap_ext)r‚ZgroupedÚitZtuplrâÚnumsrjr/rnr*Rs   zProcess.memory_mapscCs |j ¡S)z˜Return files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. )r¡Ú open_filesrÁrjrjrnr4mszProcess.open_filesÚinetcCs |j |¡S)aTReturn socket connections opened by process as a list of (fd, family, type, laddr, raddr, status) namedtuples. The *kind* parameter filters for connections that match the following criteria: +------------+----------------------------------------------------+ | Kind Value | Connections using | +------------+----------------------------------------------------+ | inet | IPv4 and IPv6 | | inet4 | IPv4 | | inet6 | IPv6 | | tcp | TCP | | tcp4 | TCP over IPv4 | | tcp6 | TCP over IPv6 | | udp | UDP | | udp4 | UDP over IPv4 | | udp6 | UDP over IPv6 | | unix | UNIX socket (both UDP and TCP protocols) | | all | the sum of all the possible families and protocols | +------------+----------------------------------------------------+ )r¡Ú connections)r‚Úkindrjrjrnr6tszProcess.connectionscCs¤|jdkrJ|jƒ‚|jdkr&tdƒ‚zt |j|¡Wnfty€trht|jƒrht|j|j|j ƒ‚nd|_ t |j|jƒ‚Yn t yžt |j|jƒ‚Yn0dS)Nrz›preventing sending signal to process with PID 0 as it would affect every process in the process group of the calling process (os.getpid()) instead of PID 0T)r|r—r’Úkillrr3rTr r€r r›rr r©r‚ZsigrjrjrnÚ _send_signals ÿ  zProcess._send_signalcCs tr| |¡n |j |¡dS)zÚSend a signal *sig* to process pre-emptively checking whether PID has been reused (see signal module constants) . On Windows only SIGTERM is valid and is treated as an alias for kill(). N)r5r:r¡Ú send_signalr9rjrjrnr;¤s zProcess.send_signalcCs tr| tj¡n |j ¡dS)zµSuspend process execution with SIGSTOP pre-emptively checking whether PID has been reused. On Windows this has the effect ot suspending all process threads. N)r5r:ÚsignalÚSIGSTOPr¡ÚsuspendrÁrjrjrnr>°szProcess.suspendcCs tr| tj¡n |j ¡dS)z²Resume process execution with SIGCONT pre-emptively checking whether PID has been reused. On Windows this has the effect of resuming all process threads. N)r5r:r<ÚSIGCONTr¡ÚresumerÁrjrjrnr@»szProcess.resumecCs tr| tj¡n |j ¡dS)z—Terminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)r5r:r<ÚSIGTERMr¡r8rÁrjrjrnÚ terminateÆszProcess.terminatecCs tr| tj¡n |j ¡dS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)r5r:r<ÚSIGKILLr¡r8rÁrjrjrnr8Ñsz Process.killcCs<|dur|dkstdƒ‚|jtur(|jS|j |¡|_|jS)aôWait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. On Windows there's no such limitation (exit code is always returned). If the process is already terminated immediately return None instead of raising NoSuchProcess. If *timeout* (in seconds) is specified and process is still alive raise TimeoutExpired. To wait for multiple Process(es) use psutil.wait_procs(). Nrz"timeout must be a positive integer)r—r¥r¤r¡Úwait)r‚ÚtimeoutrjrjrnrDÛs  z Process.wait)N)F)NN)N)NN)N)N)F)N)r$)T)r5)N)Er¶rµÚ __qualname__Ú__doc__r‘rrºÚ__repr__r¾r¿rÂÚpropertyr|Ú contextlibÚcontextmanagerr³rÙrÜrÞrrrzrªrêrár«rôr¦rõr÷r5rÆrørùrúrÄryrRrûrýrhrrrr7rr r r rŠrr[rZrÅrZdeprecated_methodr"r#r)r*r4r6r:r;r>r@rBr8rDrjrjrjrnrR$sœ  0  B ,  '         E \           rRcCs"g|]}| d¡s|dvr|‘qS)Ú_)r;r>r@rBr8rDrrÙrÜrÞrrhr"r³)rärvrjrjrnroósÿcsJeZdZdZdd„Zdd„Zdd„Zdd „Zd d „Zd‡fd d„ Z ‡Z S)rSa Same as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence: * send_signal() * terminate() * kill() This is done in order to avoid killing another process in case its PID has been reused, fixing BPO-6973. >>> import psutil >>> from subprocess import PIPE >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE) >>> p.name() 'python' >>> p.uids() user(real=1000, effective=1000, saved=1000) >>> p.username() 'giampaolo' >>> p.communicate() ('hi ', None) >>> p.terminate() >>> p.wait(timeout=2) 0 >>> cOs(tj|i|¤Ž|_|j|jjdddS)NT)r¨)Ú subprocessrSÚ_Popen__subprocrr|rrjrjrnr‘szPopen.__init__cCsttttƒttjƒƒƒSr~)rrËÚdirrSrMrÁrjrjrnÚ__dir__#sz Popen.__dir__cCst|jdƒr|j ¡|S)NÚ __enter__)rÄrNrQrÁrjrjrnrQ&s  zPopen.__enter__cOsjt|jdƒr|jj|i|¤ŽS|jr.|j ¡|jr>|j ¡z|jrP|j ¡W| ¡n | ¡0dS)NÚ__exit__)rÄrNrRÚstdoutÚcloseÚstderrÚstdinrDrrjrjrnrR+s    zPopen.__exit__c Csbzt ||¡WSty\zt |j|¡WYStyVtd|jj|fƒ‚Yn0Yn0dS)Nz!%s instance has no attribute '%s')ÚobjectÚ__getattribute__r²rNr´r¶)r‚rªrjrjrnrX;s   ÿzPopen.__getattribute__Ncs0|jjdur|jjStt|ƒ |¡}||j_|Sr~)rNÚ returncodeÚsuperrSrD)r‚rEr{©r´rjrnrDEs  z Popen.wait)N) r¶rµrFrGr‘rPrQrRrXrDÚ __classcell__rjrjr[rnrSþs rScCstt ¡ƒ}|da|S)z&Return a list of current running PIDs.r)rryrUrÚ©r{rjrjrnrURs rUcCs0|dkr dS|dkr"tr"|tƒvSt |¡SdS)z“Return True if given PID exists in the current process list. This is faster than doing "pid in psutil.pids()" and should be preferred. rFN)r5rUryrT©r|rjrjrnrTZs   rTc #s\‡‡fdd„}dd„}ttƒƒ}tt ¡ƒ}||}||}|D] }||ƒq@t2ttt ¡ƒtt  |¡ ¡ƒƒ} Wdƒn1sŠ0Y| D]¾\}} zJ| dur¶||ƒVn2|   ¡rÞˆdurÖ| j ˆˆd| _ | Vn ||ƒVWq˜t y||ƒYq˜tyT| durN|tvrNzt|VWntyJYn0n‚Yq˜0q˜dS)aReturn a generator yielding a Process instance for all running processes. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. Cached Process instances are checked for identity so that you're safe in case a PID has been reused by another process, in which case the cached instance is updated. The sorting order in which processes are yielded is based on their PIDs. *attrs* and *ad_value* have the same meaning as in Process.as_dict(). If *attrs* is specified as_dict() is called and the resulting dict is stored as a 'info' attribute attached to returned Process instance. If *attrs* is an empty list it will retrieve all process info (slow). csRt|ƒ}ˆdur |jˆˆd|_t|t|j<Wdƒn1sD0Y|S)N©rÔrÕ)rRrÙr¹rŸÚ_pmapr|)r|rß©rÕrÔrjrnr…s (zprocess_iter..addcSs4tt |d¡Wdƒn1s&0YdSr~)rŸr`r r^rjrjrnÚremoveszprocess_iter..removeNr_)rËrUr`ÚkeysrŸrrÉr¸rÑÚfromkeysrrÙr¹rrrò) rÔrÕrrbÚaÚbZnew_pidsZ gone_pidsr|r×rßrjrarnrVps@    ÿ$  ÿ rVc s ‡‡fdd„}|dur.|dks.d|}t|ƒ‚tƒ‰t|ƒ}ˆdurXtˆƒsXtdtƒ‚|durjtƒ|}|rÚ|dur€|dkr€qÚ|D]J}dt|ƒ}|durÄt|tƒ|ƒ}|dkr¸qÐ|||ƒq„|||ƒq„|ˆ}qj|rú|D]}||dƒqâ|ˆ}tˆƒt|ƒfS)a,Convenience function which waits for a list of processes to terminate. Return a (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new *returncode* attribute indicating process exit status (may be None). *callback* is a function which gets called every time a process terminates (a Process instance is passed as callback argument). Function will return as soon as all processes terminate or when *timeout* occurs. Differently from Process.wait() it will not raise TimeoutExpired if *timeout* occurs. Typical use case is: - send SIGTERM to a list of processes - give them some time to terminate - send SIGKILL to those ones which are still alive Example: >>> def on_terminate(proc): ... print("process {} terminated".format(proc)) ... >>> for p in procs: ... p.terminate() ... >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate) >>> for p in alive: ... p.kill() csXz|j|d}Wnty"Yn20|dus4| ¡sT||_ˆ |¡ˆdurTˆ|ƒdS)N)rE)rDr rrYr)rßrErY©ÚcallbackZgonerjrnÚ check_goneßs  zwait_procs..check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callablegð?)r—rËÚcallabler–rrÎÚminrÉ) ZprocsrErhrir©ÚaliveZdeadlinerßZ max_timeoutrjrgrnrW»s6$        rWTcCs.|rt ¡}nt ¡}|dur*|dkr*d}|S)azReturn the number of logical CPUs in the system (same as os.cpu_count() in Python 3.4). If *logical* is False return the number of physical cores only (e.g. hyper thread CPUs are excluded). Return None if undetermined. The return value is cached after first call. If desired cache can be cleared like this: >>> psutil.cpu_count.cache_clear() Nr)ryZcpu_count_logicalZcpu_count_physical)Zlogicalr{rjrjrnr]s  r]FcCs|s t ¡St ¡SdS)aReturn system-wide CPU times as a namedtuple. Every CPU time represents the seconds the CPU has spent in the given mode. The namedtuple's fields availability varies depending on the platform: - user - system - idle - nice (UNIX) - iowait (Linux) - irq (Linux, FreeBSD) - softirq (Linux) - steal (Linux >= 2.6.11) - guest (Linux >= 2.6.24) - guest_nice (Linux >= 3.2.0) When *percpu* is True return a list of namedtuples for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. N)ryrZZ per_cpu_timesrrjrjrnrZ0srZrcCs0t|ƒ}tr,|t|ddƒ8}|t|ddƒ8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). ZguestrZ guest_nice)Úsumr0rÒ)ÚtimesZtotrjrjrnÚ _cpu_tot_timeYs  rocCs&t|ƒ}||j8}|t|ddƒ8}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time. We do so by subtracting all idle CPU times. Ziowaitr)roZidlerÒ)rnZbusyrjrjrnÚ_cpu_busy_timels rpcCs\|j|jksJ||fƒ‚g}tjjD],}t||ƒt||ƒ}td|ƒ}| |¡q$tj|ŽS)Nr)r%ryÚ scputimesrÒÚmaxrÝ)Út1Út2Z field_deltasZfieldÚ field_deltarjrjrnÚ_cpu_times_deltas|s   rvcCsÚ|duo|dk}|dur,|dkr,td|ƒ‚dd„}|sp|rNtƒ}t |¡nt}|dur`tƒ}tƒa||tƒSg}|rŽtdd}t |¡nt}|dur¤tdd}tddat|tƒD]\}}| |||ƒ¡q¸|SdS) a¡Return a float representing the current system-wide CPU utilization as a percentage. When *interval* is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When *interval* is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately (non blocking). That means the first time this is called it will return a meaningless 0.0 value which you should ignore. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When *percpu* is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. Examples: >>> # blocking, system-wide >>> psutil.cpu_percent(interval=1) 2.0 >>> >>> # blocking, per-cpu >>> psutil.cpu_percent(interval=1, percpu=True) [2.0, 1.0] >>> >>> # non-blocking (percentage since last call) >>> psutil.cpu_percent(interval=None) 2.9 >>> NrrrcSsNt||ƒ}t|ƒ}t|ƒ}z||d}Wnty>YdS0t|dƒSdS)Nrrr)rvrorprr)rsrtÚ times_deltaÚ all_deltaZ busy_deltaZ busy_percrjrjrnÚ calculateºs  zcpu_percent..calculateTr)r—rZr‹rÚ_last_cpu_timesÚ_last_per_cpu_timesÚziprÝ©r rr!ryrsr{Ztot1rtrjrjrnr[‘s0%       r[cCsÚ|duo|dk}|dur,|dkr,td|ƒ‚dd„}|sp|rNtƒ}t |¡nt}|dur`tƒ}tƒa||tƒSg}|rŽtdd}t |¡nt}|dur¤tdd}tddat|tƒD]\}}| |||ƒ¡q¸|SdS) a·Same as cpu_percent() but provides utilization percentages for each specific CPU time as is returned by cpu_times(). For instance, on Linux we'll get: >>> cpu_times_percent() cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) >>> *interval* and *percpu* arguments have the same meaning as in cpu_percent(). NrrrcSsdg}t||ƒ}t|ƒ}dtd|ƒ}|D]0}||}t|dƒ}ttd|ƒdƒ}| |¡q(tj|ŽS)NgY@rr)rvrorrrrkrÝryrq)rsrtr3rwrxZscaleruZ field_percrjrjrnrys   z$cpu_times_percent..calculateTr)r—rZr‹rÚ_last_cpu_times_2Ú_last_per_cpu_times_2r|rÝr}rjrjrnr\ïs0       r\cCst ¡S)zReturn CPU statistics.)ryr^rjrjrjrnr^4sr^Úcpu_freqc Csºt ¡}|r|Stt|ƒƒ}|dkr(dS|dkr8|dSd\}}}d}|D]6}||j7}trl|jdurld}qJ||j7}||j7}qJ||}|r˜d} } n||} ||} t  || | ¡SdS)a9Return CPU frequency as a nameduple including current, min and max frequency expressed in Mhz. If *percpu* is True and the system supports per-cpu frequency retrieval (Linux only) a list of frequencies is returned for each CPU. If not a list with one element is returned. rNr)rrrFT) ryr€r(rÎÚcurrentr0rkrrrZscpufreq) rr{rZcurrsZminsZmaxsZset_noneZcpurZmin_Zmax_rjrjrnr€;s.      Ú getloadavgcCst ¡}|ja|S)a€Return statistics about system memory usage as a namedtuple including the following fields, expressed in bytes: - total: total physical memory available. - available: the memory that can be given instantly to processes without the system going into swap. This is calculated by summing different memory values depending on the platform and it is supposed to be used to monitor actual memory usage in a cross platform fashion. - percent: the percentage usage calculated as (total - available) / total * 100 - used: memory used, calculated differently depending on the platform and designed for informational purposes only: macOS: active + wired BSD: active + wired + cached Linux: total - free - free: memory not being used at all (zeroed) that is readily available; note that this doesn't reflect the actual memory available (use 'available' instead) Platform-specific fields: - active (UNIX): memory currently in use or very recently used, and so it is in RAM. - inactive (UNIX): memory that is marked as not used. - buffers (BSD, Linux): cache for things like file system metadata. - cached (BSD, macOS): cache for various things. - wired (macOS, BSD): memory that is marked to always stay in RAM. It is never moved to disk. - shared (BSD): memory that may be simultaneously accessed by multiple processes. The sum of 'used' and 'available' does not necessarily equal total. On Windows 'available' and 'free' are the same. )ryrXr'r&r]rjrjrnrXvs5rXcCst ¡S)aåReturn system swap memory statistics as a namedtuple including the following fields: - total: total swap memory in bytes - used: used swap memory in bytes - free: free swap memory in bytes - percent: the percentage usage - sin: no. of bytes the system has swapped in from disk (cumulative) - sout: no. of bytes the system has swapped out from disk (cumulative) 'sin' and 'sout' on Windows are meaningless and always set to 0. )ryrYrjrjrjrnrY±s rYcCs t |¡S)z£Return disk usage statistics about the given *path* as a namedtuple including total, used and free space expressed in bytes plus the percentage usage. )ryre)rârjrjrnreÆsrecCsXdd„}t |¡}trPg}|D],}|j||jdƒ||jdƒd}| |¡q|S|SdS)a3Return mounted partitions as a list of (device, mountpoint, fstype, opts) namedtuple. 'opts' field is a raw string separated by commas indicating mount options which may vary depending on the platform. If *all* parameter is False return physical devices only and ignore all others. c Ss*zt ||¡WSttfy$Yn0dSr~)r’ÚpathconfÚOSErrorr²)rârªrjrjrnrƒ×sz!disk_partitions..pathconfÚ PC_NAME_MAXÚ PC_PATH_MAX)ZmaxfileZmaxpathN)ryrdr5Ú_replaceZ mountpointrÝ)Úallrƒr{ÚnewÚitemr1rjrjrnrdÎs    þ rdcCs’trt|dni}tjfi|¤Ž}|s2|r.iSdS|r@t|dƒ}ttdtjƒ}|rt| ¡D]\}}||Ž||<qZ|S|dd„t |  ¡ŽDƒŽSdS)aØReturn system disk I/O statistics as a namedtuple including the following fields: - read_count: number of reads - write_count: number of writes - read_bytes: number of bytes read - write_bytes: number of bytes written - read_time: time spent reading from disk (in ms) - write_time: time spent writing to disk (in ms) Platform specific: - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms) - read_merged_count (Linux): number of merged reads - write_merged_count (Linux): number of merged writes If *perdisk* is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. On recent Windows versions 'diskperf -y' command may need to be executed first otherwise this function won't find any disk. )ÚperdiskNúpsutil.disk_io_countersÚsdiskiocSsg|] }t|ƒ‘qSrj©rmrvrjrjrnrorpz$disk_io_counters..) r0rÑryrcÚ _wrap_numbersrÒrrr¸r|Úvalues)r‹Únowrapr„Úrawdictr1ZdiskÚfieldsrjrjrnrcês   rcrŒzClears nowrap argument cachecCsnt ¡}|s|riSdS|r&t|dƒ}|rN| ¡D]\}}tj|Ž||<q2|Stjdd„t| ¡ŽDƒŽSdS)adReturn network I/O statistics as a namedtuple including the following fields: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD) If *pernic* is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. Núpsutil.net_io_counterscSsg|] }t|ƒ‘qSrjrŽrvrjrjrnroGrpz#net_io_counters..)ryr_rr¸rZsnetior|r)Zpernicr‘r’Znicr“rjrjrnr_#s  r_r”r5cCs t |¡S)a˜Return system-wide socket connections as a list of (fd, family, type, laddr, raddr, status, pid) namedtuples. In case of limited privileges 'fd' and 'pid' may be set to -1 and None respectively. The *kind* parameter filters for connections that fit the following criteria: +------------+----------------------------------------------------+ | Kind Value | Connections using | +------------+----------------------------------------------------+ | inet | IPv4 and IPv6 | | inet4 | IPv4 | | inet6 | IPv6 | | tcp | TCP | | tcp4 | TCP over IPv4 | | tcp6 | TCP over IPv6 | | udp | UDP | | udp4 | UDP over IPv4 | | udp6 | UDP over IPv6 | | unix | UNIX socket (both UDP and TCP protocols) | | all | the sum of all the possible families and protocols | +------------+----------------------------------------------------+ On macOS this function requires root privileges. )ryr`)r7rjrjrnr`Osr`c Csøtjdk}|rddl}t ¡}|jdd„dt t¡}|D]²\}}}}}} |r z|  |¡}Wn@t yžt r€|dkr€tj }nt tdƒrštj |krštj }Yn0|tj krÒtr²d nd } | | ¡d krÒ|d | 7}q¶|| t ||||| ¡¡q.)ÚkeyéÿÿÿÿrQú:ú-éz%s00)ÚsysrOÚsocketryraÚsortr°r rÉZ AddressFamilyr—r7rQrÄr5ÚcountrÝrZsnicaddrrÑ) Z has_enumsrœZrawlistr{rªZfamZaddrÚmaskZ broadcastZptpÚ separatorrjrjrnrals.     ÿ   racCst ¡S)aReturn information about each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a namedtuple with the following fields: - isup: whether the interface is up (bool) - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or NIC_DUPLEX_UNKNOWN - speed: the NIC speed expressed in mega bits (MB); if it can't be determined (e.g. 'localhost') it will be set to 0. - mtu: the maximum transmission unit expressed in bytes. )ryrbrjrjrjrnrbœs rbÚsensors_temperaturesc sœ‡fdd„}t t¡}t ¡}| ¡D]l\}}|r&| d¡\}}}} ||ƒ}||ƒ}|| ƒ} |rj| sj|} n | rv|sv| }|| t  |||| ¡¡q.q&t |ƒS)a<Return hardware temperatures. Each entry is a namedtuple representing a certain hardware sensor (it may be a CPU, an hard disk or something else, depending on the OS and its configuration). All temperatures are expressed in celsius unless *fahrenheit* is set to True. cs(|dur$ˆr t|ƒdddS|SdS)Né ršé )r()Ún©Ú fahrenheitrjrnÚconvert»sz%sensors_temperatures..convertr) r°r rÉryr¡r¸r rÝrZshwtemprÑ) r¦r§r{r’rªrZlabelrZhighZcriticalrjr¥rnr¡³s"  ÿÚ sensors_fanscCst ¡S)z¢Return fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). )ryr¨rjrjrjrnr¨ÙsÚsensors_batterycCst ¡S)ažReturn battery information. If no battery is installed returns None. - percent: battery power left as a percentage. - secsleft: a rough approximation of how many seconds are left before the battery runs out of power. May be POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED. - power_plugged: True if the AC power cable is connected. )ryr©rjrjrjrnr©æs cCst ¡S)zAReturn the system boot time expressed in seconds since the epoch.)ryrgrjrjrjrnrgúsrgcCst ¡S)a„Return users currently connected on the system as a list of namedtuples including the following fields. - user: the name of the user - terminal: the tty or pseudo-tty associated with the user, if any. - host: the host name associated with the entry, if any. - started: the creation time as a floating point number expressed in seconds since the epoch. )ryrfrjrjrjrnrf s rfcCst ¡S)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )ryÚwin_service_iterrjrjrjrnrª srªcCs t |¡S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )ryÚwin_service_get)rªrjrjrnr« sr«c Cs@ddlm}ddlm}tj ¡}d}gd¢}t|dƒt|ddD]ò}|j drŒtj  |j d¡}| ¡|kr€|  d ¡}q|  d ¡}nd }|j d r¸t   d t   t|j d ƒ¡¡}nd }|j dpÈd }|sötröz| ¡d}WntyôYn0|rtrd|vr| d¡d}|dd…}|j ddurF||j djƒnd } |j ddurj||j djƒnd } |j ddurŽt|j ddƒnd } |j dr¬t|j dƒnd } |j drÎd |j d¡} n |j d} |j drö|j ddd…nd }||dd…|j d| | | | |||| f }t|d|ƒd…ƒqFdS)Nr)Ú bytes2human)Úget_terminal_sizez)%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s) r|r)rªrárZr¦rÅr«r÷rô) ZUSERZPIDz%MEMZVSZZRSSZNICEZSTATUSZSTARTZTIMEZCMDLINE)rÕr¦z%H:%Mz%b%drsrZz%M:%Srôrú\r¢rÅr)r÷ráú rªr«ršé r|)rr¬Ú_compatr­rŒÚdateZtodayÚprintrVr¹rrŽr‹Ú localtimermr5rÆrr7ÚsplitÚvmsr$rrkr·)r¬r­Z today_dayZtemplrÔÚprÛZcputimerr¶r$Zmempr÷rár«ÚlinerjrjrnÚtest% sr         ÿ   ÿÿ ÿÿ ÿÿ  " ö r¹r,Ú__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r5)F)¶rGZ __future__rr°rJrŒrˆr’r<rMr›rr‹rírîrsrrrrrr r rr r±r r rrr”rrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7Z PROCFS_PATHr8ryr9r:r;r<r=Z_psutil_windowsr>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrÓÚplatformÚ__all__ÚextendZ__extra__all__rÄrRriÚglobalsZ_globalsr€rOräÚisupperrÒrÝrQÚ __author__rPrÊrµrOrr&rÚrWr¤rkÚreplaceZcextr©r·rórtrxr}rŠrrËrÈrSrUrTr`ÚLockrŸrVrWr]rZrzÚ Exceptionr{rorprvr[r~rr\r^r€r‚rXrYrerdrcÚpartialÚ cache_clearr_r`rarbr¡r¨r©rgrfrªr«r¹rmrwr¶rjrjrjrnÚs¾                                                                           0    ÿ ÿÿ  ÿÿ   Uÿ T K ^      Z E  (   ;  /ÿ 'ÿ 0       =