]*j_X dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddlmZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlm 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"lm.Z.dd#lm/Z/dd$lm0Z0dd%lm1Z1dd&lm2Z2dd'lm3Z3dd(lm4Z4dd)lm5Z5dd*lm6Z6dd+lm7Z7dd,lm8Z8dd-lm9Z9dd.lm:Z:dd/lm;Z;dd0lmZ>dd3lm?Z?dd4lm@Z@dd5lmAZBe!r!d6ZCdd7lmDZEdd8lDmFZFdd9lDmGZGdd:lDmHZHdd;lDmIZIne9rIddlKmMZMdd?lKmNZNdd@lKmOZOddAlKmPZPddBlKmQZQddClJmRZRddDlJmSZSddElJmTZTddFlJmUZUddGlJmVZVnLe"rddHlmWZEnCerddIlmXZEn:e8rddJlmYZEddKlYmZZZddLlYm[Z[d6ZCn#er ddMlm\ZEd6ZCndNe jdOZ^e_e^gdPZ`e`jeEjeceEjdQrleeZfdZgeheEjD]LZgegjdRsegjs&eleEjegefeg<e`jegN[f[geEjZndSZodTZpeqdUepjdVDZsele dWe jZtdaudavewZxeyepjdVdXeleEjdYdk7rdZeEjjd[Z^e^d\z Z^eceEjdYr>dVje}e~eEjjZe^d]ed^epd_z Z^n e^d`epd_z Z^eleEjdadbZe^dcez Z^e^ddz Z^e e^eceEdereEjZndfZdgZdhZGdidjZdehedDchc]}|jdkr|dlvs|c}ZGdmdnedZdoZdpZiaeZddqZdre_dsej_ddtZddvZddwZ e j$j&eiZ e j$j&eduxiZdyZdzZd{Zdd|Zej7Zej7Zdd}Zd~ZeceEdrddZe`jdeceds eceEdr5ecedrejBZn eEjBZe`jddZdZdZddZddZejNeBjde_dej_ddZejNeBjde_dej_ddZdZdZeceEdrddZe`jdeceEdrdZe`jdeceEdrdZe`jddZdZe9rdZdZeceEdr(dZdZe`jde`jddZ[@y#e $rdZ YSwxYwcc}w#e$riZYwxYw#e$riZYwxYw)a;psutil 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 Supported Python versions are cPython 3.6+ and PyPy. N)_common)_ntuples)AIX)BSD) 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)FREEBSD)LINUX)MACOS)NETBSD)NIC_DUPLEX_FULL)NIC_DUPLEX_HALF)NIC_DUPLEX_UNKNOWN)OPENBSD)OSX)POSIX)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)SUNOS)WINDOWS) AccessDenied)Error) NoSuchProcess)TimeoutExpired) ZombieProcess)debug)memoize_when_activated) wrap_numbersz/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_HIGH) IOPRIO_LOW) IOPRIO_NORMAL)IOPRIO_VERYLOW)_psosx)_psbsd)_pssunos) CONN_BOUND) CONN_IDLE)_psaixz platform z is not supported)Gr/r0r2r.r1 version_info __version__r%r"r&r!r'r(r+r r*r#r)r#r$r rrr r rrr rrr rAF_LINKrrrrrrrrrrrrrr,r-rProcessPopen pid_existspids process_iter wait_procsvirtual_memory swap_memory cpu_times cpu_percentcpu_times_percent cpu_count cpu_statsnet_io_countersnet_connections net_if_addrs net_if_statsdisk_io_countersdisk_partitions disk_usageusers boot_timerlimitRLIMzGiampaolo Rodola'z7.2.2c#2K|]}t|ywN)int).0nums @/opt/hc_python/lib64/python3.12/site-packages/psutil/__init__.py rns@)?#SX)?. monotonicversionzversion conflict: z C extension z.module was built for another version of psutilz (z instead of )z (different than __file__z%the existing psutil install directoryz9; you may try to 'pip uninstall psutil', manually remove z1 or clean the virtual env somehow, then reinstallppid_mapci}tD])} tj|j||<+|S#tt f$rY?wxYw)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )rS _psplatformrPppidr0r2)retpids rm _ppid_mapr|sW6C &..s388:C  "=1  s&;A  A ctj}t||z }|dkrdnd}tjj|j |S)z(Format seconds in a human readable form.iQz%H:%M:%Sz%Y-%m-%d %H:%M:%S)timerjdatetime fromtimestampstrftime)secsnowsecs_agofmts rm _pprint_secsrsK ))+C3:H </*5HC    * *4 0 9 9# >>cdttj}||vrd|d|}t|y)z+Check net_connections()'s `kind` parameter.zinvalid kind argument z; valid ones are: N)tupler conn_tmap ValueError)kindkindsmsgs rm_check_conn_kindrs< '## $E 5&th.@Horc,eZdZdZdCdZdDdZdZdZeZdZ dZ d Z d Z e d Zej d ZdEd ZdZdZdZedZdZdZdZdZdZdZdZdCdZe redZ!dZ"dZ#dZ$e%e&jNdrdZ(e%e&jNd rdEd!Z)e%e&jNd"rdCd#Z*e%e&jNd$rdCd%Z+e%e&jNd&rd'Z,e%e&jNd(rd)Z-e.rd*Z/d+Z0d,Z1e%e&jNd-rd.Z2dDd/Z3dCd0Z4ed1Z5ed2Z6d3Z7dFd4Z8e%e&jNd5rdGd6Z9d7Z:dHd8Z;ee rd<Z?d=Z@d>ZAd?ZBd@ZCdAZDdCdBZEy)IrPaRepresents 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 that the PID of the process being queried has been reused. That means that you may end up retrieving information for another process. 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. Nc&|j|yri)_init)selfr{s rm__init__zProcess.__init__9s  3rc|tj}n6|dkrd|d}t| tjj |||_d|_ d|_ d|_ d|_ d|_ d|_tj |_d|_tj&||_d|_d|_t.|_|j2df|_ |j7|_y#t $r}d}t|||d}~wwxYw#t8$rYyt:$rYyt$r|sd}t||dd|_ YywxYw) Nrz$pid must be a positive integer (got rtzprocess PID out of rangerFzprocess PID not foundT)osgetpidrrxcextcheck_pid_range OverflowErrorr0_pid_name_exe _create_time_gone _pid_reused_hash threadingRLock_lock_ppidrP_proc_last_sys_cpu_times_last_proc_cpu_times _SENTINEL _exitcoder{_ident _get_identr.r2)rr{ _ignore_nsprerrs rmrz Process._init<sP ;))+CQw>Z   ,".t/@/@"AY%%))'' DJJLALDAqaS! >;K$5rc|jS)zThe process PID.)rrs rmr{z Process.pidsyyrc#K|j5t|drdn |jj||jj||j j|t r|jj||jjd|jj||jj||j j|t r|jj||jjdddy#|jj||jj||j j|t r|jj||jjwxYw#1swYyxYww)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) rhasattrrXcache_activate memory_inforyruidsr oneshot_entercache_deactivate oneshot_exitrs rmrzProcess.oneshotsR6ZZtX& .NN11$7$$33D9II,,T2 006JJ,,.NN33D9$$55d;II..t4 2248JJ++-MZBNN33D9$$55d;II..t4 2248JJ++-MZs6 G%GBE3B G? G%BGGG"G%c Jt}|t|tttt fsdt |}t|t |}||z }|rJdjt|dkDrdnddjtt|}t|i}|xs|}|j5|D]-} |dk(r |j} nt!||} | } | ||</ ddd|S#t"t$f$r|} Y%t&$r|rY[wxYw#1swY|SxYw) aUtility 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 zinvalid attr name{} {}rsrrrr{)_as_dict_attrnamesrlistrset frozensettype TypeErrorrlenrmapreprrrr{getattrr.r2NotImplementedError) rattrsad_value valid_namesr invalid_namesretdictlsrrzmeths rmas_dictzProcess.as_dict!s.)  edE3 %BC+DK=9n$JE!K/M.55}-1CrIIc$ 67!o%  !k \\^u}"hh&tT2"f!$ !$%m4#"C* $s<6D=%C4"D4DD DDDDD"c"ttn td}|j|k(ry|j}|Et |jj } t |}|j |kr|Syy#t $rYywxYw)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_PIDrSr{ryrPrr0)r lowest_pidry proc_ctimeparents rmrzProcess.parentPs %0$;[ 88z !yy{  !*668J  %%':5!M6 !  s B B Bcvg}|j}|$|j||j}|$|S)zReturn the parents of this process as a list of Process instances. If no parents are known return an empty list. )rappend)rparentsprocs rmrzProcess.parentsfs@{{} NN4 ;;=Drc2|js |jry |t|jk7|_|jr4tj |jt |jy#t$rYyt $r d|_YywxYw)zReturn whether this process is running. It also checks if PID has been reused by another process, in which case it will remove the process from `process_iter()` internal cache and return False. FT)rrrPr{ _pids_reusedaddr0r2rs rmrzProcess.is_runningqs ::))  $wtxx'88D   *#DHH--  DJ sAA99 BBBc|jtr|jjS|jxs|jj|_|jS)z`The process parent PID. On Windows the return value is cached after first call. )rrrryrrs rmryz Process.ppidsI !!# ::??$ $8tzz'8DJ:: rctr|j |jS|jj}trWt |dk\rI |j }|r6tjj|d}|j|r|} ||_||j_|S#ttf$rY+wxYw)z>The process name. The return value is cached after first call.r) r-rrrrrcmdlinerpathbasename startswithr.r2)rrr  extended_names rmrz Process.names tzz-:: zz  SY"_ -,,.$&GG$4$4WQZ$@M$//5,   !-0    sB00CCcfd}j: jj}|s ||}|_jSjS#t$rY*wxYw#t$r}||cYd}~Sd}~wwxYw)zThe process executable as an absolute path. May also be an empty string. The return value is cached after first call. cbj}|rttdryttdri|d}tjj |rEtjj |r&tj |tjr|St|tr||S)NaccessX_OKr) r rrr isabsisfilerrrr.)fallbackr exers rmguess_itzProcess.exe..guess_its{llnG72x0WR5Haj GGMM#&s+ #rww/J(L1OrN)r)rrrr.)rrrrs` rmrz Process.exes  & 99  jjnn&&4  yytyy(  .-- .s.A( A A%$A%( B1A?9B?Bc6|jjS)z3The command line this process has been called with.)rr rs rmr zProcess.cmdlineszz!!##rcb |jjS#t$r tcYSwxYw)z2The process current status as a STATUS_* constant.)rrr2r+rs rmrzProcess.statuss/ !::$$& & !  !s ..ctrMt d}t||jj} tj |j S|jjS#t$rt|cYSwxYw)ztThe name of the user that owns the process. On UNIX this is calculated by using *real* process uid. z0requires pwd module shipped with standard python) rpwd ImportErrorrrealgetpwuidpw_nameKeyErrorstrrusername)rrreal_uids rmr"zProcess.usernamesw {H!#&&yy{''H %||H-555 ::&&( (  %8}$ %sA..BBcp|j|jj|_|jS)awThe process creation time as a floating point number expressed in seconds since the epoch (seconds since January 1, 1970, at midnight UTC). The return value, which is cached after first call, is based on the system clock, which means it may be affected by changes such as manual adjustments or time synchronization (e.g. NTP). )rrrrs rmrzProcess.create_times1    $ $ 6 6 8D    rc6|jjS)z6Process current working directory as an absolute path.)rcwdrs rmr&z Process.cwdszz~~rc||jjS|j|jj|y)z'Get or set process niceness (priority).N)rnice_getrnice_set)rvalues rmnicez Process.nices8 =::&&( (  % % ' JJ   &rc6|jjS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rrrs rmrz Process.uids!s ::??$ $rc6|jjS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgidsrs rmr.z Process.gids(s::??$ $rc6|jjS)zVThe terminal associated with this process, if any, else None. )rterminalrs rmr0zProcess.terminal.s::&&( (rc6|jjS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fdsrs rmr2zProcess.num_fds4::%%' 'r io_countersc6|jjS)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. )rr4rs rmr4zProcess.io_counters=s::))+ +r ionice_getc|)| d}t||jjS|j|jj ||S)aGet 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. z$'ioclass' argument must be specified)rrr6r ionice_set)rioclassr*rs rmionicezProcess.ioniceIsT$@C$S/)zz,,..))+zz,,We<rrr@rrangerrXcpu_affinity_setr)rcpuss rm cpu_affinityzProcess.cpu_affinityrs|c$**"="="?@AA))+tzz+?@#zz<<>$U3y/E+F%GH ++DTO>> 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. )rr|rPr{rrrr0r2r defaultdictrrpopr) r recursivervrrzr{rychildreverse_ppid_mapseenstack child_pidintimes rmchildrenzProcess.childrens4 !!#;TXX&224 %^^- T488# ' &):):)<<JJu-.L 5 +66t< %^^- T &--c2.5DXXJEiik$; !1#!6I  ' 2",u/@/@/B!B!JJu-!LL3"7& =*=98*=9s%)/E2)AF2FFFFc |duxr|dkD}||dkrd|d}t|txsd fd}|rX|}|jj}t j ||}|jj}nL|j }|j}|}|jj}||||_||_y|j|jz |j|jz z} ||z } ||_||_ | | z dz} | z} t| dS#t$rYywxYw) 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 >>> Nrinterval is not positive (got rtrctzSri)_timer)num_cpussrmtimerz"Process.cpu_percent..timer*s8h& &rd) rr[rrXr~sleeprrusersystemroundZeroDivisionError)rintervalblockingrrest1pt1st2pt2 delta_proc delta_timeoverall_cpus_percentsingle_cpu_percentrds @rmrYzProcess.cpu_percents_F4':HsN  HqL28,a@CS/ !;#! ' 'C**&&(C JJx 'C**&&(C**C++C'C**&&(C{ck+.(,/)hh)cjj3::.EF 3Y #& $'! 0%/$;s#B ("6!@ +Q/ /)!  s%D>> E  E c6|jjS)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. )rrXrs rmrXzProcess.cpu_times^szz##%%rc6|jjS)aReturn a namedtuple with variable fields depending on the platform, representing memory information about the process. The "portable" fields available on all platforms are `rss` and `vms`. All numbers are expressed in bytes. )rrrs rmrzProcess.memory_infoiszz%%''rc6|jjS)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. )rmemory_full_infors rmryzProcess.memory_full_infotszz**,,rcttjj}||vrd|dt |}t ||tj jvr |jn |j}|}t||}txstj}|dkDsd|d}t ||t|z dzS)aCompare 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') zinvalid memtype z; valid types are rz]can't calculate process memory percent because total physical system memory is not positive (rtrf)r_ntppfullmem_fieldsrrpmemrryr _TOTAL_PHYMEMrVtotalfloat)rmemtype valid_typesrfunmetricsr* total_phymems rmmemory_percentzProcess.memory_percents4==001 + %"7+.+&)+ S/ !$))+++   && %)%>(8(>(> a33?2B!E S/ !l++s22r memory_mapscf|jj}|rXi}|D]*}|d}|dd} ttd|||||<,|Dcgc]}t j |g||c}S|Dcgc]}t j|c}S#t$r|||<YwxYwcc}wcc}w)aReturn 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'). Nc ||zSrir)xys rmz%Process.memory_maps..sAr)rrrrr r{ pmmap_grouped pmmap_ext)rgroupeditdtuplr numsrs rmrzProcess.memory_mapss'')BD7D8D'"&s+=qw'M"N$ HIIqt**4:!D':qII467Bq*B77 $'"&$'I7sB B)9B.B&%B&c6|jjS)zReturn files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. )r open_filesrs rmrzProcess.open_filess zz$$&&rcNt||jj|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 | +------------+----------------------------------------------------+ )rrr^rrs rmr^zProcess.net_connectionss!, zz))$//rr^) replacementc&|j|S)Nr)r^rs rm connectionszProcess.connectionss###..rc|jdkrJ|j|j|j|j|j}}}|dk(r d}t | t j ||y#t$r8}trt|rt||||d|_ t|||d}~wt$r}t|||d}~wwxYw)Nrzpreventing 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{rrrrrkillProcessLookupErrorrrRr2rr0PermissionErrorr.)rsigr{ryrrrs rm _send_signalzProcess._send_signalsxx!| -TXX -#  % % '"hh DJJtCaxE !o% 7S!% 8z#(T48cA! #C.C7" 7"3-36 7s$(A?? C3B;; C CCctr|j|y|j|tjk7r4|j s$d}t |j|j||jj|y)zSend 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(). zprocess no longer existsrN) rrrsignalSIGTERMrr0r{rr send_signal)rrrs rmrzProcess.send_signalsd    c "  % % 'fnn$T__->0#DHHdjjcBB JJ " "3 'rctr |jtjy|j |j j y)zSuspend process execution with SIGSTOP pre-emptively checking whether PID has been reused. On Windows this has the effect of suspending all process threads. N)rrrSIGSTOPrrsuspendrs rmrzProcess.suspends5    fnn -  % % ' JJ   rctr |jtjy|j |j j y)zResume process execution with SIGCONT pre-emptively checking whether PID has been reused. On Windows this has the effect of resuming all process threads. N)rrrSIGCONTrrresumers rmrzProcess.resumes5    fnn -  % % ' JJ   rctr |jtjy|j |j j y)zTerminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)rrrrrrrrs rm terminatezProcess.terminate)s3    fnn -  % % ' JJOO rctr |jtjy|j |j j y)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)rrrSIGKILLrrrrs rmrz Process.kill4s3    fnn -  % % ' JJOO rc|jdk(r d}t||Ft|ttfsdt |d}t ||dkrd|d}t||jtur |jS |jj||_|jS#t$r*}t||j|j}||d}~wwxYw)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. If *timeout=0* either return immediately or raise TimeoutExpired (non-blocking). To wait for multiple Process objects use psutil.wait_procs(). rzcan't wait for PID 0Nz%timeout must be an int or float (got rtz&timeout must be positive or zero (got )r{r) r{rrrjrrrrrrwaitr1r)rtimeoutrrexcs rmrz Process.wait>s" 88q=(CS/ !  gU|4=d7m_ANn${>wiqI o% >> *>> ! !ZZ__W5DN ~~   dhhTZZHC3  s B00 C#9%CC#riFNN)rssTinet)Frr __qualname____doc__rrrr__repr__rrrrpropertyr{ contextlibcontextmanagerrrrrrr4ryrrr rr"rr&r+rrr.r0r2rrxrPr4r:rfrGrHrJr-rMrOrQrRr^rYrXrryrrrr^rdeprecated_methodrrrrrrrrrrrmrPrPsC6-^!2F<H+*! ? @.@.D-^, :$>(T$!)$ ! '  %  %  %  )  ({""M2 ,{""L1 =,{""H- 7{""$67 =({""I. ({""I. (  , - ({""I. (HT[0z&&((- "3H{""M2 82'02W+<=/>/   72 ( !   %rrP_>rrrrrfrrrrr^rrrrcBeZdZdZdZdZdZdZdZdfd Z xZ S) rQaSame 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 >>> ctj|i||_|j|jjdy)NT)r) subprocessrQ_Popen__subprocrr{rargskwargss rmrzPopen.__init__s5$))4:6: 4>>%%4 8rcxttttttjzSri)rCrdirrQrrs rm__dir__z Popen.__dir__s&c#e*s:+;+;'<<=>>rcft|jdr|jj|S)N __enter__)rrrrs rmrzPopen.__enter__s% 4>>; / NN $ $ & rct|jdr|jj|i|S|jr|jj |j r|j j  |j r|j j |jy#|jwxYw)N__exit__)rrrstdoutclosestderrstdinrrs rmrzPopen.__exit__s 4>>: .*4>>**D;F; ;{{ !!#{{ !!# ::JJ$$&  s &B77C c tj||S#t$rN tj|j|cYS#t$r|jd|}t|dwxYwwxYw)Nz has no attribute )object__getattribute__AttributeErrorrr)rrrs rmrzPopen.__getattribute__sw 4**46 6 4 4..t~~tDD! 4**> $ $ 0>>,, ,gl7#$'! rri) rrrrrrrrrr __classcell__)rs@rmrQrQvs+:9?  4rrQcJttj}|da|S)z&Return a list of current running PIDs.r)rCrxrSrrzs rmrSrSs% !!# $Ca&K Jrcf|dkry|dk(rtr |tvStj|S)zReturn True if given PID exists in the current process list. This is faster than doing "pid in psutil.pids()" and should be preferred. rF)rrSrxrR)r{s rmrRrRs6  Qw e df}%%c**rc# K fd} fd}tj tt}t j }||z }||z }|D] }|| t r1t j }td|||t r1 tt jttj|jz} | D].\}} | ||} || j||| _| 0 ay#t$r ||YHwxYw# awxYww)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. Cache can optionally be cleared via `process_iter.cache_clear()`. 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). c<t|}||j<|Sri)rPr{)r{rpmaps rmrzprocess_iter..addss|TXX rc*j|dyri)rV)r{rs rmremovezprocess_iter..removes drz+refreshing Process instance for reused PID N)rr)_pmapcopyrrSkeysrrVr3rCrrdictfromkeysrrr0) rrrrabnew_pids gone_pidsr{rrrs @rmrTrTs%(  ::>> 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() c |j|}||js$||_j| |yyy#tt jf$rYywxYw)N)r)rrrrr1r)rrrcallbackgones rm check_gonezwait_procs..check_goneGsq #73J%T__->",'TN( .? 9 9:   sA A('A(rz(timeout must be a positive integer, got z callback z is not a callableg?)rcallablerrrcrminr) procsrrrralivedeadliner max_timeoutrs ` @rmrUrU"sJ #7a<8 BoHX$6(%78n 5D JE8g%   7a< DE *K"x&(2[Aa<4)4- % ( D tQ   JU $$rTcn|rtj}ntj}||dkrd}|S)alReturn the number of logical CPUs in the system (same as os.cpu_count()). 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)rxcpu_count_logicalcpu_count_cores)logicalrzs rmr[r[s8++-))+ 37 JrcV|stjStjS)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. )rxrX per_cpu_timesrAs rmrXrXs%, $$&&((**rrAcht|}tr |t|ddz}|t|ddz}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). guestr guest_nice)sumrr)timestots rm _cpu_tot_timer s= e*C  wugq)) wulA.. JrcZt|}||jz}|t|ddz}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time. We do so by subtracting all idle CPU times. iowaitr)r idler)rbusys rm_cpu_busy_timers6  DEJJD GE8Q ''D Krc|j|jk(s J||fg}tjjD]8}t||t||z }t d|}|j |:tj|S)Nr)r}r{ scputimesrmaxr)t1t2 field_deltasfield field_deltas rm_cpu_times_deltasrs :: #-b"X- #L''b%(72u+== ![) K(( >>< ((rcxtjj}|duxr|dkD}||dkrd|d}t|d}|sd|r t }t j |n!tj|xs t }t t|<||t|Sg}|r"t d}t j |n#tj|xs t d}t dt|<t|t|D]\}} |j||| |S) aReturn 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 >>> Nr`rrartct||}t|}t|} ||z dz}t|dS#t$rYywxYw)Nrfrr`)rr rrjrk)rr times_delta all_delta busy_delta busy_percs rm calculatezcpu_percent..calculate&sY'B/ !+. #K0  '#i/36IA& &!  s8 AATrA) rcurrent_threadidentrrXr~rg_last_cpu_timesget_last_per_cpu_timeszipr rlrBtidrmrrrrztot1rs rmrYrYs"F  " " $ * *Ct#63H1 .xj:o '  B JJx  $$S)8Y[B({_S122 D)D JJx &**3/I9D3ID#,D#9C $ 3C 89FB JJyR( ): rcxtjj}|duxr|dkD}||dkrd|d}t|d}|sd|r t }t j |n!tj|xs t }t t|<||t|Sg}|r"t d}t j |n#tj|xs t d}t dt|<t|t|D]\}} |j||| |S) aSame 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(). Nr`rrartcg}t||}t|}dtd|z }|D]:}||z}t|d}t td|d}|j |<t j|S)NgY@rr`)rr rrjrrr{r)rrrrrscaler field_percs rmrz$cpu_times_percent..calculatebs'B/ !+. Ay))&K$u,Jz1-JSj159J KK # ' ~~t$$rTrA) rrr rrXr~rg_last_cpu_times_2r"_last_per_cpu_times_2r$rr%s rmrZrZOs#  " " $ * *Ct#63H1 .xl!<o%$  B JJx "&&s+:y{B!*#.s344 D)D JJx (,,S1KYd5KD%.d%;c"$ 5c :;FB JJyR( )< rc*tjS)zReturn CPU statistics.)rxr\rrrmr\r\s  ""rcpu_freqcvtj}|r|Stt|}|dk(ry|dk(r|dSd\}}}d}|D]D}||jz }t r|j d}'||j z }||jz }F||z }|rdx} } n ||z } ||z } tj|| | S)a:Return CPU frequency as a namedtuple 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)r`r`r`FT) rxr/rrcurrentrrrr{scpufreq) rBrzrdcurrsminsmaxsset_nonecpur1min_max_s rmr/r/s""$ JSXH1}Q1v $1!tT CS[[(E#' CGGODCGGOD (*"&&D4(?D(?D}}WdD99r getloadavgcFtj}|ja|S)aReturn 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. )rxrVrrrs rmrVrVs!j  $ $ &CIIM Jrc*tjS)aReturn 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. )rxrWrrrmrWrWs  " " $$rc,tj|S)zReturn disk usage statistics about the given *path* as a namedtuple including total, used and free space expressed in bytes plus the percentage usage. )rxrc)r s rmrcrcs  ! !$ ''rc,tj|S)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. )rxrb)alls rmrbrb$s  & &s ++rc<tr t|ni}tjdi|}|s|riSdS|r t |d}|r/|j D]\}}t j|||<|St jdt|jDS)aReturn 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. )perdiskNpsutil.disk_io_countersc32K|]}t|ywri)r)rkrs rmrnz#disk_io_counters..[sE.Dc!f.Dror) rrrxra _wrap_numbersrr{sdiskior$values)rAnowraprrawdictdiskfieldss rmrara0s@',T' "F**4V4G r&$& )BC#MMOLD& LL&1GDM,||Ec7>>3C.DEFFrrBzClears nowrap argument cachec<tj}|s|riSdS|r t|d}|r/|jD]\}}t j |||<|St j t |jDcgc] }t|c}Scc}w)acReturn 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. "net_io_counters.cache_clear()" can be used to invalidate the cache. Npsutil.net_io_counters) rxr]rDrr{snetior$rFr)pernicrGrHnicrJrs rmr]r]is4))+G r%% )AB "==?KC;;/GCL+{{S'..2B-CD-CSV-CDEEDsBrLcBt|tj|S)aReturn 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. )rrxr^rs rmr^r^s4T  & &t ,,rc|tj}|jdtjt }|D]\}}}}}} t j|}|tjk(r;trdnd}|j|dkr||dz }|j|dkrtj|||||} trM|t j t j"hvr+ t%j&| }|| j)|  ||j/| t1|S#t$rStr|dk(rtj}n3ttdr#|tjk(rtj}Y6wxYw#t*$r} t-| Yd } ~ d } ~ wwxYw) a*Return the addresses associated to each NIC (network interface card) installed on the system as a dictionary whose keys are the NIC names and value is a list of namedtuples for each address assigned to the NIC. Each namedtuple includes 5 fields: - family: can be either socket.AF_INET, socket.AF_INET6 or psutil.AF_LINK, which refers to a MAC address. - address: is the primary address and it is always set. - netmask: and 'broadcast' and 'ptp' may be None. - ptp: stands for "point to point" and references the destination address on a point to point interface (typically a VPN). - broadcast: and *ptp* are mutually exclusive. Note: you can have more than one address of the same family associated with each interface. c |dS)Nrrrs rmrznet_if_addrs..sqtr)keyrO:-00N) broadcast)rxr_sortrrUrsocket AddressFamilyrr-rOrrcountr{snicaddrAF_INETAF_INET6rbroadcast_addr_replace Exceptionr3rr) rawlistrzrfamaddrmaskrZptp separatorntrs rmr_r_s$&&(G LL^L$  ! !$ 'C18-c4y# *&&s+C +%% % %#I**Y'!+9+R((**Y'!+]]3dIs ; sv~~v?? 5#2226 (KK)K4 D G29J 9E *3"9!)) Y/C;;N;N4N ")) *4 c  s+D>3F>AFF F;& F66F;c*tjS)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. )rxr`rrrmr`r`s  # # %%rsensors_temperaturesc fd}tjt}tj}|j D]p\}}|s |j d\}}}} ||}||}|| } |r| s|} n| r|s| }||jtj|||| |rhrt|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. c:|rt|dzdz dzS|Sy)N rX )r)n fahrenheits rmconvertz%sensors_temperatures..convert s,}2<a1 q(B.C!Crr) rrUrrxrmrrVrr{shwtempr) rsrtrzrHrrFlabelr1highcriticals ` rmrmrm s D%%d+224#MMOLD&17A.wh!'*t}"8,#Hd#DD   eWdH!MN,Cyr sensors_fansc*tjS)zReturn fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). )rxryrrrmryry. s ''))rsensors_batteryc*tjS)aReturn 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. )rxr{rrrmr{r{; s**,,rc*tjS)a!Return the system boot time expressed in seconds since the epoch (seconds since January 1, 1970, at midnight UTC). The returned value is based on the system clock, which means it may be affected by changes such as manual adjustments or time synchronization (e.g. NTP). )rxrerrrmrereO s  ""rc*tjS)aReturn 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. )rxrdrrrmrdrdY s    rc*tjS)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )rxwin_service_iterrrrmrrm s++--rc,tj|S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )rxwin_service_get)rs rmrrs s**400r heap_infocJtjtjS)aReturn low-level heap statistics from the C heap allocator (glibc). - `heap_used`: the total number of bytes allocated via malloc/free. These are typically allocations smaller than MMAP_THRESHOLD. - `mmap_used`: the total number of bytes allocated via `mmap()` or via large ``malloc()`` allocations. - `heap_count` (Windows only): number of private heaps created via `HeapCreate()`. )r{pheaprxrrrrmrr szz;00233rc,tjy)aRequest that the underlying allocator free any unused memory it's holding in the heap (typically small `malloc()` allocations). In practice, modern allocators rarely comply, so this is not a general-purpose memory-reduction tool and won't meaningfully shrink RSS in real programs. Its primary value is in **leak detection tools**. Calling `heap_trim()` before taking measurements helps reduce allocator noise, giving you a cleaner baseline so that changes in `heap_used` come from the code you're testing, not from internal allocator caching or fragmentation. Its effectiveness depends on allocator behavior and fragmentation patterns. N)rx heap_trimrrrmrr s rrcddl}t||j_tj j t|y)zZEnable or disable PSUTIL_DEBUG option, which prints debugging messages to stderr. rN)psutil._commonboolr PSUTIL_DEBUGrxr set_debug)r*psutils rm _set_debugr s/"&u+FNNtE{+rrrr)NF)FTr)rrrr functoolsrrr\rsysrr~rrrrrrr{rrrr r r r r rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5rD PROCFS_PATHr6rxr7r8r9r:r;_psutil_windowsr<r=r>r?r@rArBrCrDrErFrGrHrIrJrKrLplatformrr__all__extend__extra__all__rrPglobals_globalsrrrr isupperrrrO __author__rNrsplitrMrcrrrrrjreplacerurrr!rsrwhatrvr|rrrrQrSrRrrrrT cache_clearrUr[rXrr r!rdr#r rrrYrr,r-rZr\r/r:rVrWrcrbrapartialr]r^r_r`rmryr{rerdrrrrrrSs0rmrs~     $!%##" ""#$$'') & ""#$#(#""!"#"+2K))++) +<<4468+'&)* '' )$#K'K cll^#4 5C c ""- b{))* ;  )yH E[%%&   F # %k&6&6>HUO NN5 !' %     @):):3)?@@ {DII .  H {3#$i) {//88;= IC ;;C{+ HHT#k..6678 9 A3l;-q11 ";-q11 / D  Ftf MMC >>C c  ; #$$I ?FFX"7|!1<<#4 : A|LGLh+$ u 3l1 #I  Y%B.+8/y//177EO    "(()4*@&  )*I\$((*+0028v#  ; #&:P NN: 2| \ Br< ]]  ++  NN< 8v %*( ,+G\ 1y008 (F$$FN0i//7'E#-<:z &* ;./@ NN)* ;'* NN>" ;)* - NN$%# $ . 1 ; $4  $ NN; NN; ,eL CJ*` OsGY=Z Z $Z 0$Z&Z=ZZZZZ)(Z)