mfR| dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z n #e$rdZ YnwxYwddlmZddlmZddlmZddlmZdd 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;lHmJZJddlHmMZMneFrIdd?lmNZIdd@lOmPZPddAlOmQZQddBlOmRZRddClOmSZSddDlOmTZTddElOmUZUddFlNmVZVddGlNmWZWddHlNmXZXddIlNmYZYddJlNmZZZnGe@rddKlm[ZIn>e=rddLlm\ZIn5eErddMlm]ZIddNl]m^Z^ddOl]m_Z_d9ZGnerrsAAA3c#hhAAA. monotonicversionzOversion conflict: %r C extension module was built for another version of psutil__file__z (cg|]}|Srmrmroxs rqrrrrs???Aa???rsz instead of )z (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 reinstallppid_mapci}tD]C} tj|||<-#tt f$rY@wxYw|S)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )rV _psplatformrSppidr r )retpids rq _ppid_maprsm66  C &.s3388::C!=1     s)>AAcFtjfd}|S)zpDecorator which raises NoSuchProcess in case a process is no longer running or its PID has been reused. cx|st|j|j|g|Ri|SN) is_runningr r_name)selfargskwargsfuns rqwrapperz'_assert_pid_not_reused..wrapper sI   6$*55 5s4)$)))&)))rs) functoolswraps)rrs` rq_assert_pid_not_reusedrs:_S***** Nrsctj}t||z }|dkrd}nd}tj||S)z(Format seconds in a human readable form.iQz%H:%M:%Sz%Y-%m-%d %H:%M:%S)timerndatetime fromtimestampstrftime)secsnowsecs_agofmts rq _pprint_secsrsX )++C3:H,!   * *4 0 0 9 9# > >>rsc|eZdZdZdEdZdFdZdZeZdZdZ d Z e d Z e jd ZdGd Zd ZdZdZedZdZdZdZdZdZdZdZdEdZeredZdZ dZ!dZ"e#e$j%drdZ&e#e$j%drdGd Z'e#e$j%d!rdEd"Z(e#e$j%d#rdEd$Z)e#e$j%d%rd&Z*e#e$j%d'rd(Z+e,rd)Z-d*Z.d+Z/e#e$j%d,rd-Z0e1dFd.Z2dEd/Z3ed0Z4ed1Z5e6j7d23d4Z8d5Z9dHd7Z:e#e$j%d8rdId:Z;d;ZZ>e1d?Z?e1d@Z@e1dAZAe1dBZBe1dCZCdEdDZDdS)KrSa'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 Nc0||dSr)_init)rrs rq__init__zProcess.__init__Es 3rsFc|tj}nMts.t|tt fst d|z|dkrtd|z||_d|_ d|_ d|_ d|_ d|_ tj|_d|_t%j||_d|_d|_t.|_ |nE#t4$rYn9t6$rYn.t8$r"|sd|z}t9|d|d|_ YnwxYw|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)osgetpid_PY3 isinstancernr TypeError ValueError_pidr_exe _create_time_gone_hash threadingRLock_lock_ppidrrS_proc_last_sys_cpu_times_last_proc_cpu_times _SENTINEL _exitcode create_timerr r r_ident)rr _ignore_nspmsgs rqrz Process._initHs ;)++CC I 3d < < I AC GHHHQww !J#&"'(((      _&&  !(-- #' $(!" "           D    D " " " "4s:#Cs333!  "x!23 s!C66 D8 D8 (D87D8c  tj}n#t$ri}YnwxYw|j|d<|jr |j|d<|5 ||d<||d<n0#t$rd|d<Ynt$rd|d<Ynt$rYnwxYw|j tdfvr |j |d<|j rt|j |d<|jjd|jjd d d |Dd cdddS#1swxYwYdS) Nrnamestatuszombie terminatedexitcodestartedrt(, c"g|] \}}|d| S)=rm)rokvs rqrrz#Process.__str__..s'EEE1aaa+EEErsr|) collections OrderedDictAttributeErrorrroneshotrrr r rrrrr __class__ __module____name__joinitems)rinfos rq__str__zProcess.__str__xs *,,DD   DDD hU : &:DL \\^^ H H #yy{{V !%X  * * *!)X  . . .!-X    ~i%666#'>Z   B".t/@"A"AY)))''' EE EEEFFFFH H H H H H H H H H H H H H H H H H Hs[ %%E .BE B5E B5'E ) B52E 4B55BE  EEcZt|tstS|j|jkSr)rrSNotImplementedrrothers rq__eq__zProcess.__eq__s+%)) "! !{el**rsc||k Srrmrs rq__ne__zProcess.__ne__s5=  rscP|jt|j|_|jSr)rhashrrs rq__hash__zProcess.__hash__s# : dk**DJzrsc|jS)zThe process PID.)rrs rqrz Process.pids yrsc#K|j5t|drdVn |j||j||j|t r|j||j dV|j ||j ||j |t r|j ||j n#|j ||j ||j |t r|j ||j wxYwddddS#1swxYwYdS)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) rhasattrr[cache_activate memory_inforr6uidsr oneshot_entercache_deactivate oneshot_exitrs rqrzProcess.oneshots 6Z& .& .tX&&% . .N11$777$33D999I,,T2227 00666J,,...EEEN33D999$55d;;;I..t4449 224888J++---- N33D999$55d;;;I..t4449 224888J++----M& .& .& .& .& .& .& .& .& .& .& .& .& .& .& .& .& .& .s+GB D7.B G7B GGGGc t}|t|tttt fst dt|zt |}||z }|rPtdt|dkrdnddd tt|t}|p|}|5|D]X} |d kr|j}nt!||} | }n'#t"t$f$r|}Ynt&$r|rYOwxYw|||<Y dddn #1swxYwY|S) 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 %szinvalid attr namersrv rr)_as_dict_attrnamesrlisttupleset frozensetrtyperlenrmapreprdictrrgetattrrr NotImplementedError) rattrsad_value valid_names invalid_namesretdictlsrrmeths rqas_dictzProcess.as_dicts)  edE3 %BCC G 7$u++ EFFFJJE!K/M : j}--11CCr99IIc$ 66777"9:::&&  !k \\^^ $ $ $ $u}}"h&tT22"dff$m4###"CCC*H !$ ! $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$sBE#(D  E D0E! D0-E/D00 EE  E c2ttntd}|j|krdS|}|Q|} t |}||kr|SdS#t $rYdSwxYwdS)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_PIDrVrrrrSr )r lowest_pidrctimeparents rqrzProcess.parents %0$;[[ 8z ! !4yy{{  $$&&E  %%''500!M10!      s(B BBcg}|}|+|||}|+|S)zReturn the parents of this process as a list of Process instances. If no parents are known return an empty list. )rappend)rparentsprocs rqrzProcess.parents-sJ{{}} NN4 ;;==Drsc|jrdS |t|jkS#t$rYdSt$r d|_YdSwxYw)zReturn whether this process is running. It also checks if PID has been reused by another process in which case return False. FT)rrSrr r rs rqrzProcess.is_running8ss : 5  748,,, ,   44   DJ55 s# AAActr|jS|jp|j|_|jS)z`The process parent PID. On Windows the return value is cached after first call. )r6rrrrs rqrz Process.ppidPs@  :??$$ $8tz'8'8DJ: rsctr|j|jS|j}trwt |dkrd |}|rThe process name. The return value is cached after first call.Nr) r8rrrr6rcmdlinerpathbasename startswithr)rrr  extended_names rqrz Process.namebs  tz-: z    -SYY"__  -,,..-$&G$4$4WQZ$@$@M$//55-,         s B B*)B*cfd}je j}|s ||}n#t$rYnwxYw|_n##t$r}||cYd}~Sd}~wwxYwjS)zThe process executable as an absolute path. May also be an empty string. The return value is cached after first call. c}|rttdr|ttdrg|d}tj|r@tj|r!tj|tjr|St|tr||S)NaccessX_OKr) r rrr isabsisfilerrrr)fallbackr exers rqguess_itzProcess.exe..guess_itsllnnG 72x00 WR5H5H ajGMM#&&s++ #rw//J(L11 OrsN)r)rrrr)rrrerrs` rqrz Process.exe|s      " 9  jnn&&&h444'   . . .x--------- .ys,A 8 AA A0 A+%A0+A0c4|jS)z3The command line this process has been called with.)rr rs rqr zProcess.cmdlinesz!!###rscd |jS#t$r tcYSwxYw)z2The process current status as a STATUS_* constant.)rrr r-rs rqrzProcess.statussB !:$$&& & ! ! !  !s //ctrhttd|j} tj|jS#t$rt|cYSwxYw|j S)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) r6pwd ImportErrorrrealgetpwuidpw_nameKeyErrorstrrusername)rreal_uids rqr"zProcess.usernames  ){!FHHHyy{{'H %|H--55 % % %8}}$$$ %:&&(( (sAA-,A-cZ|j|j|_|jS)zThe process creation time as a floating point number expressed in seconds since the epoch. The return value is cached after first call. )rrrrs rqrzProcess.create_times,   $ $ 6 6 8 8D   rsc4|jS)z6Process current working directory as an absolute path.)rcwdrs rqr&z Process.cwdsz~~rsc||jS|st|j|j|j|dS)z'Get or set process niceness (priority).N)rnice_getrr rrnice_set)rvalues rqnicez Process.nices] =:&&(( (??$$ :#DHdj999 J   & & & & &rsc4|jS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rrrs rqrz Process.uidss :??$$ $rsc4|jS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgidsrs rqr.z Process.gidss:??$$ $rsc4|jS)zVThe terminal associated with this process, if any, else None. )rterminalrs rqr0zProcess.terminals:&&(( (rsc4|jS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fdsrs rqr2zProcess.num_fdss:%%'' 'rs io_countersc4|jS)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. )rr3rs rqr3zProcess.io_counterss:))++ +rs ionice_getc|*|td|jS|j||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. Nz$'ioclass' argument must be specified)rrr5 ionice_set)rioclassr*s rqionicezProcess.ionicesJ$$%KLLLz,,...z,,We<<>$U3y/E/E/E+F+F%G%GHH ++DTOO<<<<>> 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. )rrrrSrrr r r defaultdictrrpopadd) r recursiver}rrrchildreverse_ppid_mapseenstack child_pidintimes rqchildrenzProcess.childrenhs6;;& %^^--   T48## '  ++--1B1B1D1DDDJJu---)=9$  +6t<< %^^-- 3 3 T &--c222255DXJE iikk$;; !1#!6  I  ' 2 2"&!1!1!3!3u7H7H7J7J!J!4JJu---!LL333)=9# & s%ABBBA%F&&F:9F:c| |duo|dk}||dkrtd|ztpd fd}|r[|}|j}t j||}|j}nE|j}|j}|}|j}||||_||_dS|j|jz |j |j z z}||z } ||_||_ || z dz} | z} t| dS#t$rYdSwxYw)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 >>> Nr!interval is not positive (got %r)rc&tzSr)_timer)num_cpussrqtimerz"Process.cpu_percent..timers88h& &rsd) rr^rr[rsleeprrusersystemroundZeroDivisionError) rintervalblockingrest1pt1st2pt2 delta_proc delta_timeoverall_cpus_percentsingle_cpu_percentrds @rqr\zProcess.cpu_percentsF4':HsN  HqLL@8KLL L;;#! ' ' ' ' '  %''C*&&((C Jx %''C*&&((CC*C+C%''C*&&((C{ck+.(,/)sh)cj3:.EF 3Y #& $'! 0&0*%<$C ("6!@ +Q// /)!   33 sD-- D;:D;c4|jS)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. )rr[rs rqr[zProcess.cpu_times sz##%%%rsc4|jS)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. )rrrs rqrzProcess.memory_infosz%%'''rsr) replacementc*|Sr)rrs rqmemory_info_exzProcess.memory_info_ex s!!!rsc4|jS)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 rqr|zProcess.memory_full_info$sz**,,,rsrsscttjj}||vr"t d|dt ||tjjvr|jn|j}|}t||}tptj }|dkst d|z|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 (%r)rf)rrpfullmem_fieldsrrpmemrr|r _TOTAL_PHYMEMrYtotalfloat)rmemtype valid_typesrmetricsr* total_phymems rqmemory_percentzProcess.memory_percent4s;/788 + % %*{+++-.. .")[-=-E"E"Ed  ! #%%))%>(8(8(> aD   l+++s22rs memory_mapsTc:|j}|rei|D]E}|d}|dd} td|||<1#t$r||<YBwxYwtjfdDStjfd|DS)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 ||zSrrm)r{ys rqz%Process.memory_maps..ds 1q5rsc.g|]}|g|RSrmrm)ror dnts rqrrz'Process.memory_maps..hs/999t4*!D'***999rscg|]}|Srmrm)ror{rs rqrrz'Process.memory_maps..ks+++1A+++rs)rrrr r pmmap_grouped pmmap_ext)rgroupedittuplr numsrrs @@rqrzProcess.memory_mapsRs''))B ,''D7D8D'"%&8&8!D'4"H"H$#'''"&$' .99999q9999 *++++++++sAA%$A%c4|jS)zReturn files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. )r open_filesrs rqrzProcess.open_filesms z$$&&&rsinetc6|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)rkinds rqrzProcess.connectionsts,z%%d+++rsc|jdkrJ|j|jdkrtd tj|j|dS#t$r]t r4t |jr t|j|j|j d|_ t|j|jt$rt|j|jwxYw)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)rrrkillrr4rUr rrrr rrrsigs rq _send_signalzProcess._send_signalsx!|||TX||#x1}} EFFF 9#&&&&&% > > >>z$(33>($*djIII!%DJ'$*===" 9 9 9"48TZ888 9s AB Ccvtr||dS|j|dS)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(). N)r6rr send_signalrs rqrzProcess.send_signalsB  (   c " " " " " J " "3 ' ' ' ' 'rsctr!|tjdS|jdS)zSuspend process execution with SIGSTOP pre-emptively checking whether PID has been reused. On Windows this has the effect ot suspending all process threads. N)r6rsignalSIGSTOPrsuspendrs rqrzProcess.suspendsB  !   fn - - - - - J   rsctr!|tjdS|jdS)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)r6rrSIGCONTrresumers rqrzProcess.resumesB    fn - - - - - J       rsctr!|tjdS|jdS)zTerminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)r6rrSIGTERMrrrs rq terminatezProcess.terminates@     fn - - - - - JOO     rsctr!|tjdS|jdS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)r6rrSIGKILLrrrs rqrz Process.kills@     fn - - - - - JOO     rsc||dkstd|jtur|jS|j||_|jS)aWait 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)rrrrwait)rtimeouts rqrz Process.waitsS  w!||ABB B > * *> !11~rsrFNN)r}Tr)Err __qualname____doc__rrr__repr__rrrpropertyr contextlibcontextmanagerrrrrrrrrrr rr"rr&r+r6rr.r0r2rrrSr3r9rirFrGrIr8rLrNrPrQrr^r\r[rrdeprecated_methodrzr|rrrrrrrrrrrrmrsrqrSrS$s'@.4.4.4.4`HHH6H+++!!! X @.@.@.D****X&   0"4%%%N$$$!!!)))$!!!   '''' (  % %  %  % % %  ) ) )  ( ( (w{"M22 , , , ,w{"L11= = = = =(w{"H-- 7 7 7 7 7w{"$677= = = = =&w{"I.. ( ( ( (w{"I..( ( ( ( , , , , --- (((w{"I..( ( ( (CCCCJZ0Z0Z0Z0x&&&(((W=999"":9"--- 3333:w{"M22, , , , ,6''',,,,4 9 9 9 9* ( ( (!!!   rsrScDg|]}|d|dv|S)_)rrrrrrrrrrr^rirzr)r rzs rqrrrrsH$$$1ALL$5$5$!#;#;#Q;#;#;#rscBeZdZdZdZdZdZdZdZd fd Z xZ S) rTa 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 >>> cttj|i||_||jjddS)NT)r) subprocessrT_Popen__subprocrrrrrs rqrzPopen.__init__s<$)4:6:: 4>%4 88888rscttttttjzSr)rBrdirrTrrs rq__dir__z Popen.__dir__#s.c#e**s:+;'<'<<==>>>rscbt|jdr|j|S)N __enter__)rrrrs rqrzPopen.__enter__&s/ 4>; / / ' N $ $ & & & rscpt|jdr|jj|i|S|jr|j|jr|j |jr|j|dS#|wxYw)N__exit__)rrrstdoutclosestderrstdinrrs rqrzPopen.__exit__+s 4>: . . *4>*D;F;; ;{ $ !!###{ $ !!### :'J$$&&&  s ) BB5c t||S#t$rQ t|j|cYS#t$r t|jjd|dwxYwwxYw)Nz instance has no attribute '')object__getattribute__rrrr)rrs rqrzPopen.__getattribute__;s H**466 6 H H H H..t~tDDDDD! H H H$(,(?(?(?&GHHH H Hs  A8A A8 *A44A8Nc|jj |jjStt||}||j_|Sr)r returncodesuperrTr)rrrrs rqrz Popen.waitEsE > $ 0>, ,E4  %%g..$'! rsr) rrrrrrrrrr __classcell__)rs@rqrTrTs:999???  HHHrsrTcVttj}|da|S)z&Return a list of current running PIDs.r)rBrrVrrs rqrVrVRs( !## $ $Ca&K Jrsct|dkrdS|dkrtr|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)r6rVrrUrs rqrUrUZs@  Qwwu e dff}%c***rsc #NKfd}d}tt}tt}||z }||z }|D] }||t5t t tt t |z} dddn #1swxYwY| D]\}} | ||VnD| r#| | _ | Vn ||V[#t$r||Yrt$r0| *|tvr! t|Vn#t$rYnwxYwYwxYwdS)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). ct|}||_t5|t|j<dddn #1swxYwY|S)Nrr)rSrrr_pmapr)rrrrs rqrVzprocess_iter..addss||   58 DDDI  # #"E$(O # # # # # # # # # # # # # # # sAAAc|t5t|dddddS#1swxYwYdSr)rrrUrs rqremovezprocess_iter..removes  ! ! IIc4  ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s 155Nr)rrVrkeysrrBrrrfromkeysrrrr rr ) rrrVrabnew_pids gone_pidsrrrs `` rqrWrWpsO*!!! DFF A EJJLLA1uHAIs ;; D''x00668899:;;;;;;;;;;;;;;;;; T |c#hh??$$#($(LL"'(%1%<%< JJJJ#c((NNN    F3KKKKK   |u *$$$$D  !sP0A.C**C.1C.=AEF")F">F F" FF"FF"!F"c<  fd}||dksd|z}t|t t|}&tstdtz|t |z}|ri||dkrn`|D]V}dt |z }|4t |t z |}|dkrn|||J|||W| z }|i|r|D]}||d| z }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() c ||}||s-||_| |dSdSdS#t$rYdSwxYw)N)r)rrrrVr )rrrcallbackgones rq check_gonezwait_procs..check_gones #733J%T__->->%",'HTNNNNN(' &%    DD sA A,+A,Nrz*timeout must be a positive integer, got %szcallback %r is not a callableg?)rrcallablerrcrminr) procsrrrralivedeadliner max_timeoutrs ` @rqrXrXsH # # # # # #7a<<:WDoo 55D JJEHX$6$67(BCCC88g%   7a<<  . .DE *K"x&((2[AAa<<E 4)))) 4---- % (   D JtQ      JJU $$rsTcl|rtj}ntj}||dkrd}|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)rcpu_count_logicalcpu_count_physical)logicalrs rqr^r^sA/+--,.. 377 JrsFcR|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. )rr[ per_cpu_timesr@s rqr[r[0s*, +$&&&(***rsr@ct|}tr(|t|ddz}|t|ddz}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). guestr guest_nice)sumr1r)timestots rq _cpu_tot_timerYsJ e**C / wugq))) wulA... Jrsc`t|}||jz}|t|ddz}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time. We do so by subtracting all idle CPU times. iowaitr)ridler)rbusys rq_cpu_busy_timerls:   DEJD GE8Q ' ''D Krsc|j|jks J||fg}tjjD]H}t||t||z }t d|}||Itj|S)Nr)rr scputimesrmaxr)t1t2 field_deltasfield field_deltas rq_cpu_times_deltasr|s : # # #b"X # # #L&.))b%((72u+=+== ![)) K((((  , //rsc&|duo|dk}||dkrtd|zd}|s[|r#t}tj|nt}|t}ta||tSg}|r%td}tj|nt }|td}tdat |t D]$\}}||||%|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`rract||}t|}t|} ||z dz}t|dS#t$rYdSwxYw)Nrfrr`)rrrrjrk)r r  times_delta all_delta busy_delta busy_percs rq calculatezcpu_percent..calculatesu'B// !+.. #K00  '#i/36IA&& &!   33 sA AATr@)rr[rrg_last_cpu_times_last_per_cpu_timesziprrlrArmrr rtot1r s rqr\r\sJJt#63H1 >> 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`rrac g}t||}t|}dtd|z }|D]J}||z}t|d}t td|d}||Kt j|S)NgY@rr`)rrr rjrrrr )r r rrrscaler field_percs rqrz$cpu_times_percent..calculates'B// !+.. Ay)))& $ $K$u,Jz1--JSj11599J KK # # # #$d++rsTr@)rr[rrg_last_cpu_times_2_last_per_cpu_times_2rrrs rqr]r]sKt#63H1 .pathconfs@ ;tT** *(    DD s ,, PC_NAME_MAX PC_PATH_MAX)maxfilemaxpath)rrer6_replace mountpointr)allr6rnewitemrs rqreres  %c * *C   D -@@ -@@BBB JJrNNNN  rscftrt|ni}tjdi|}|s|rindS|rt |d}t tdt j}|r$|D] \}}||||<|S|dt| DS)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_counterssdiskioc,g|]}t|Srmrrzs rqrrz$disk_io_counters..s;;;qCFF;;;rsrm) r1rrrd _wrap_numbersrrrDrrvalues)rBnowraprrawdictrdiskfieldss rqrdrds@', 3T' " " " "F*44V44G '&rr$& D)BCC i 9 9B=#MMOO ( (LD&BKGDMMr;;C)9)9$:;;;<.GsGGG1AGGGrs)rr`rGrrsnetiorrH)pernicrIrJnicrLs rqr`r`#s4)++G &%rr% C)ABB I"==?? 3 3KC">62GCLL~GGW^^5E5E0FGGGHHrsrNrc*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. )rra)rs rqraraOs4  &t , ,,rsc tjdk}|rddl}tj}|dt jt}|D]\}}}}}} |rr | |}n[#t$rNtr|dkr tj }n1ttdrtj |kr tj }YnwxYw|tj krEtrdnd } || d kr!|d | zz }|| d k!||t#j||||| t'|S) 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. )rrNc|dS)Nrrm)r{s rqrznet_if_addrs..s qtrs)keyrR:-z%s00)sysrPsocketrrbsortrrTr AddressFamilyrr8rRrr6countrrsnicaddrr) has_enumsr]rawlistrrfamaddrmask broadcastptp separators rqrbrbls$ F*I &((G LL^^L$$$  !$ ' 'C18LL-c4y#  . .**3// . . ..sbyy%-CCk955.#+s22&-C . +% % % %-#I**Y''!++****Y''!++ D )#tT9cJJKKKK 99s)A??ACCc(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. )rrcrmrsrqrcrcs  # % %%rssensors_temperaturesc fd}tjt}tj}|D]\}}|rz|d\}}}} ||}||}|| } |r| s|} n| r|s| }||tj |||| |zt|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. cD|rt|dzdz dzn|SdS)N r[ )r)n fahrenheits rqconvertz%sensors_temperatures..converts3}2<Ca1 q(B..!C}rsr) rrTrrrkrrUrrshwtempr) rqrrrrJrrHlabelr'highcriticals ` rqrkrks  D D D D D%d++244#MMOO E ELD& E17A.wh!''**wt}}"78,,$$#HH$d$#DD   OE7D(CCEEE ECyyrs 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). )rrwrmrsrqrwrws ')))rssensors_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. )rryrmrsrqryrys*,,,rsc(tjS)zAReturn the system boot time expressed in seconds since the epoch.)rrhrmrsrqrhrhs  " ""rsc(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. )rrgrmrsrqrgrg s    rsc(tjS)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )rwin_service_iterrmrsrqr~r~ s+---rsc*tj|S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )rwin_service_get)rs rqrr s*4000rsc ddlm}ddlm}tj}d}gd}t|dzt|dD]}|j drntj |j d}||kr| d }n| d }nd }|j d r@tj d tj t|j d }nd }|j dpd }|s3tr, |d}n#t"$rYnwxYw|r&t$rd|vr|dd}|dd}|j d||j djnd } |j d||j djnd } |j dt-|j ddnd } |j drt/|j dnd } |j dr!d|j d} n |j d} |j dr|j dddnd }||dd|j d| | | | |||| f z}t|d|ddS)Nr) bytes2human)get_terminal_sizez)%-10s %5s %5s %7s %7s %5s %6s %6s %6s %s) rrrr r[rrrr+r") USERPIDz%MEMVSZRSSNICESTATUSSTARTTIMECMDLINE)rrz%H:%Mz%b%drvr[z%M:%Sr"r\rnrrr+r rrrr[ r)rr_compatrrdatetodayprintrWrrrr localtimerr6rrr8splitvmsr}rjrnr)rr today_daytemplrprcputimerhrr}mempr+r rlines rqtestr% sW$$$$$$****** ##%%I 7E I I IE %9 9::: %$ / / /0-0- 6-  %33AF=4IJJEzz||y((w//v..E 6+  mG$(N3qvk7J3K3K$L$LNNGGGvj!'R   vvxx{      'G ' ::d##A&DBQBx F= ! -k!&/344435  F= ! -k!&/344435  F# $ 0QV,-q11168 &'fVn"""" 6)  %hhqvi011GGfVnG)*)9A!"1"%%r "I F5M           d*%%''**+,,,,a0-0-s<E E$#E$r__main__rrr)NF)FTr)r __future__rrrrrrrrr\rrrrrvrrrrr r r rGr rr rrrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8 PROCFS_PATHr9rr:r;r<r=r>_psutil_windowsr?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrplatform__all__extend__extra__all__rrSrjglobals_globalsrrr isupperrrrR __author__rQrrrPrcrrrrrnreplacecextrrr!rwr}rrrrrrTrVrUrLockrrWrXr^r[r Exceptionrrrrr\r"r#r]r_r%r0rYrZrfrerdpartial cache_clearr`rarbrcrkrwryrhrgr~rrrpr{rrmrsrqrs)     JJJJ CCC!!!!!!++++++""""""######222222""""""$$$$$$'''''' $$$$$$!!!!!!%%%%%%############"""""" """"""""""""######$$$$$$$$$$$$'''''''''''')))))) &&&&&& """"""""""""######$$$$$$######((((((######""""""""""""1MK))))))))))))++++++++++++))))))) %M++++++<<<<<<<<<<<<444444444444666666888888++++++******&&&&&&))))))''''''' M'''''''M''''''' M))))))$$$$$$######KKM''''''KK  !>??? @ @ @ @+++O O % 33 H  *7 9 9 ::C >>C +c   7; ##$II      ??? JJJJJfJJJ\S$$G $$$%%LLLLLGLLLh+++$  HHHHVV%V%V%V%|.++++8ikkOOOOO#)4000 &    000*TTTTt$+BBBBJ###  7; ##*&=&=&=&=P NN: 72|! \ B B!wr<  ,]  +  NN<   888v % % %*(((8,=,=,=,=^ 1y08 : :'E$$I$I$I$IN0i/799&D#----:---` & & &* 7;.//"+@ NN)*** 7;'' #*** NN>""" 7;)**& - - - NN$%%%###   $ 1... 111:-:-:-zHA Q zDFFFFFs37AA& Q11Q;:Q;? R RR