PNG  IHDR;IDATxܻn0K )(pA 7LeG{ §㻢|ذaÆ 6lذaÆ 6lذaÆ 6lom$^yذag5bÆ 6lذaÆ 6lذa{ 6lذaÆ `}HFkm,mӪôô! x|'ܢ˟;E:9&ᶒ}{v]n&6 h_tڠ͵-ҫZ;Z$.Pkž)!o>}leQfJTu іچ\X=8Rن4`Vwl>nG^is"ms$ui?wbs[m6K4O.4%/bC%t Mז -lG6mrz2s%9s@-k9=)kB5\+͂Zsٲ Rn~GRC wIcIn7jJhۛNCS|j08yiHKֶۛkɈ+;SzL/F*\Ԕ#"5m2[S=gnaPeғL lذaÆ 6l^ḵaÆ 6lذaÆ 6lذa; _ذaÆ 6lذaÆ 6lذaÆ RIENDB` 3 pe4@sdZddlmZdZdZeddejdDZdd d d d d dddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7g1Zdd8l Z dd8l Z dd8l Z dd8l Z dd8l Z dd8lZdd8lZy dd8lZWnek rd8ZYnXdd9lmZdd:lmZmZmZmZdd;lmZmZddlm0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;e jj?Z@dd@l>mAZAmBZBddAl>mCZCmDZDmEZEmFZFe@jGrddBlHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTdd8lHZHy eHjUZUWneVk rXYnXy eHjWZWWneVk rzYnXy eHjXZXWneVk rYnXy eHjYZYWneVk rYnXy eHjZZZWneVk rYnX[Hne jsr.Error NoSuchProcess AccessDeniedTimeoutExpired version_info __version__STATUS_RUNNING STATUS_IDLESTATUS_SLEEPINGSTATUS_DISK_SLEEPSTATUS_STOPPEDSTATUS_TRACING_STOP STATUS_ZOMBIE STATUS_DEAD STATUS_WAKING STATUS_LOCKEDSTATUS_WAITINGCONN_ESTABLISHED CONN_SYN_SENT CONN_SYN_RECVCONN_FIN_WAIT1CONN_FIN_WAIT2CONN_TIME_WAIT CONN_CLOSECONN_CLOSE_WAIT CONN_LAST_ACK CONN_LISTEN CONN_CLOSING CONN_NONEProcessPopen pid_existspids process_iter wait_procsvirtual_memory swap_memory cpu_times cpu_percentcpu_times_percent cpu_countnet_io_countersnet_connectionsdisk_io_countersdisk_partitions disk_usageusers boot_timeN)memoize)propertycallablelong defaultdict)wrapsPY3)deprecated_method deprecatedsdiskiosnetio) rrrrrrrrrrrr) rrrrrr r!r"r#r$r%r&linux)phymem_buffers cached_phymem)IOPRIO_CLASS_NONEIOPRIO_CLASS_RTIOPRIO_CLASS_BEIOPRIO_CLASS_IDLE) RLIM_INFINITY RLIMIT_AS RLIMIT_CORE RLIMIT_CPU RLIMIT_DATA RLIMIT_FSIZE RLIMIT_LOCKSRLIMIT_MEMLOCK RLIMIT_NOFILE RLIMIT_NPROC RLIMIT_RSS RLIMIT_STACKwin32)ABOVE_NORMAL_PRIORITY_CLASSBELOW_NORMAL_PRIORITY_CLASSHIGH_PRIORITY_CLASSIDLE_PRIORITY_CLASSNORMAL_PRIORITY_CLASSREALTIME_PRIORITY_CLASS)CONN_DELETE_TCBdarwinfreebsdsunos) CONN_IDLE CONN_BOUNDzplatform %s is not supportedposixnt monotonicc@seZdZdZdS)r zQBase exception class. All other psutil exceptions inherit from this one. N)__name__ __module__ __qualname____doc__rrrrr sc@s"eZdZdZdddZddZdS)r zaException raised when a process with a certain PID doesn't or no longer exists (zombie). NcCsVtj|||_||_||_|dkrR|r>d|jt|jf}n d|j}d||_dS)Nz(pid=%s, name=%s)z(pid=%s)zprocess no longer exists )r __init__pidnamemsgrepr)selfrmrnrodetailsrrrrls  zNoSuchProcess.__init__cCs|jS)N)ro)rqrrr__str__szNoSuchProcess.__str__)NN)rhrirjrkrlrsrrrrr s c@s"eZdZdZdddZddZdS)r z@Exception raised when permission to perform an action is denied.NcCshtj|||_||_||_|dkrd|dk rH|dk rHd|t|f|_n|dk r^d|j|_nd|_dS)Nz(pid=%s, name=%s)z(pid=%s))r rlrmrnrorp)rqrmrnrorrrrls zAccessDenied.__init__cCs|jS)N)ro)rqrrrrsszAccessDenied.__str__)NNN)rhrirjrkrlrsrrrrr s c@s"eZdZdZdddZddZdS)r zWRaised on Process.wait(timeout) if timeout expires and process is still alive. NcCsrtj|||_||_||_d||_|dk rR|dk rR|jd|t|f7_n|dk rn|jd|j7_dS)Nztimeout after %s secondsz (pid=%s, name=%s)z (pid=%s))r rlsecondsrmrnrorp)rqrurmrnrrrrls  zTimeoutExpired.__init__cCs|jS)N)ro)rqrrrrsszTimeoutExpired.__str__)NN)rhrirjrkrlrsrrrrr s cstfdd}|S)zpDecorator which raises NoSuchProcess in case a process is no longer running or its PID has been reused. cs&|jst|j|j|f||S)N) is_runningr rm_name)rqargskwargs)funrrwrappersz'_assert_pid_not_reused..wrapper)_wraps)rzr{r)rzr_assert_pid_not_reusedsr}c@seZdZdZdddZdddZdd Zd d Zd d ZddZ ddZ gdfddZ ddZ ddZ eddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zdd*d+Zerd,d-Zd.d/Zd0d1Zd2d3Zeej d4rd5d6Z!eej d7r dd8d9Z"eej d:r$dd;d<Z#eej d=r
d?Z$e%rJd@dAZ&dBdCZ'dDdEZ(dFdGZ)e*ddHdIZ+ddJdKZ,dLdMZ-dNdOZ.dPdQZ/dRdSZ0ddUdVZ1dWdXZ2ddZd[Z3erd\d]Z4e*d^d_Z5e*d`daZ6e*dbdcZ7e*dddeZ8e*dfdgZ9ddhdiZ:e;e<Z=e>djdkdldmZ?e>dndkdodpZ@dqe=krfe>dqdkdrdsZAe>dqdkdtduZBe>dvdkdwdxZCe>dydkdzd{ZDe>d|dkd}d~ZEe>ddkddZFd4e=kre>d4dkddZGde=kre>ddkddZHe>ddkdddZIe>ddkddZJe>ddkddZKe>ddkddZLe>ddkddZMe>ddkddZNde=krpe>ddkddZOde=kre>ddkddZPe>ddkddZQe>ddkddZRd:e=kre>d:dkddZSe>d:dkddZTe>ddkddZUe>ddkddZV[=dS)r'a-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|j|dS)N)_init)rqrmrrrrl'szProcess.__init__Fc Cs|dkrtj}n6t r4t|ttf r4td||dkrHtd|||_d|_ d|_ d|_ d|_ d|_ d|_tj||_d|_d|_y |jWnFtk rYn4tk r|sd|}t|d|nd|_ YnX|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 isinstancerr= TypeError ValueError_pidrw_exe _create_time_gone_hash_ppid _psplatformr'_proc_last_sys_cpu_times_last_proc_cpu_times create_timer r rm_ident)rqrm _ignore_nsprorrrr~*s6     z Process._initc Csty|j}t|j}Wn:tk r4d|j}Yn*tk rPd|j}YnXd||f}d|jj|jj|fS)Nz(pid=%s (terminated))z(pid=%s)z(pid=%s, name=%s)z%s.%s%s)rmrprnr r __class__rirh)rqrmrnrrrrrrsTs zProcess.__str__cCsd|jt|fS)Nz <%s at %s>)rsid)rqrrr__repr__aszProcess.__repr__cCst|tstS|j|jkS)N)rr'NotImplementedr)rqotherrrr__eq__ds zProcess.__eq__cCs ||k S)Nr)rqrrrr__ne__kszProcess.__ne__cCs|jdkrt|j|_|jS)N)rhashr)rqrrr__hash__ns  zProcess.__hash__c CsFtddddddddd d d g }t}t|p:d d t|D}x|D]}|jdrVqF|jdrbqF|jdrd||ddf}tj|tdd|dd}||krqF|dkrd}tj|tddd}||krqF||krqFy"t||}t|r|} n|} Wn8t k r|} Yn t k r4|r.wFYnX| ||<qFW|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 exception is raised when retrieving that particular process information. send_signalsuspendresume terminatekillwaitrvas_dictparentchildrenrlimitcSsg|]}|jds|qS)get) startswith)rxrrrrsz#Process.as_dict.._Zset_Zget_z$%s() is deprecated; use %s() insteadN)category stacklevelgetcwdz)getcwd() is deprecated; use cwd() insteadcwd) setdictdirrwarningswarnDeprecationWarninggetattrr<r NotImplementedError) rqattrsad_valueZexcluded_namesZretdictZlsrnroattrretrrrrusJ         zProcess.as_dictc CsJ|j}|dk rFy t|}|j|jkr.|SWntk rDYnXdS)zReturn the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None. N)ppidr'rr )rqrrrrrrszProcess.parentc Cs8|jr dSy|t|jkStk r2d|_dSXdS)zReturn whether this process is running. It also checks if PID has been reused by another process in which case return False. FTN)rr'rmr )rqrrrrvszProcess.is_runningcCs|jS)zThe process PID.)r)rqrrrrmsz Process.pidcCs.tr|jjS|jdkr$|jj|_|jSdS)z`The process parent PID. On Windows the return value is cached after first call. N)_POSIXrrr)rqrrrrs    z Process.ppidc Cs||jdkrv|jj}trht|dkrhy |j}Wntk rDYn$X|rhtjj |d}|j |rh|}||j_||_|jS)z>The process name. The return value is cached after first call.Nr) rwrrnrlencmdliner rpathbasenamer)rqrnrZ extended_namerrrrns    z Process.namecsfdd}jdkrzyjj}Wn&tk rJtjd}||dSX|sty||d}Wntk rrYnX|_jS)zThe process executable as an absolute path. May also be an empty string. The return value is cached after first call. csdj}|rRttdrRttdrR|d}tjj|rRtjj|rRtj|tjrR|St|t r`||S)NaccessX_OKr) rhasattrrrisabsisfilerrrr )fallbackrexe)rqrrguess_its   zProcess.exe..guess_itN)r)rrrr sysexc_info)rqrrerrr)rqrrs    z Process.execCs |jjS)z3The command line this process has been called with.)rr)rqrrrr%szProcess.cmdlinecCs |jjS)z2The process current status as a STATUS_* constant.)rstatus)rqrrrr)szProcess.statuscCs4tr&tdkrtdtj|jjjS|jjSdS)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) rpwd ImportErrorgetpwuiduidsrealZpw_namerusername)rqrrrr-s zProcess.usernamecCs|jdkr|jj|_|jS)zThe process creation time as a floating point number expressed in seconds since the epoch, in UTC. The return value is cached after first call. N)rrr)rqrrrr:s  zProcess.create_timecCs |jjS)z6Process current working directory as an absolute path.)rr)rqrrrrCsz Process.cwdcCs8|dkr|jjS|js(t|j|j|jj|dS)z'Get or set process niceness (priority).N)rZnice_getrvr rmrwZnice_set)rqvaluerrrniceGs  z Process.nicecCs |jjS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rr)rqrrrrRsz Process.uidscCs |jjS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgids)rqrrrrXsz Process.gidscCs |jjS)zVThe terminal associated with this process, if any, else None. )rterminal)rqrrrr^szProcess.terminalcCs |jjS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fds)rqrrrrdszProcess.num_fds io_counterscCs |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. )rr)rqrrrrmszProcess.io_counters ionice_getcCs4|dkr"|dk rtd|jjS|jj||SdS)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' must be specified)rrrZ ionice_set)rqioclassrrrrioniceys  zProcess.ionicercCs&|dkr|jj|S|jj||SdS)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 only. N)rr)rqresourcelimitsrrrrs  zProcess.rlimitcpu_affinity_getcCs"|dkr|jjS|jj|dS)zGet 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]). N)rrZcpu_affinity_set)rqcpusrrr cpu_affinitys zProcess.cpu_affinitycCs |jjS)z\Return the number of handles opened by this process (Windows only). )r num_handles)rqrrrrszProcess.num_handlescCs |jjS)zkReturn the number of voluntary and involuntary context switches performed by this process. )rnum_ctx_switches)rqrrrrszProcess.num_ctx_switchescCs |jjS)z2Return the number of threads used by this process.)r num_threads)rqrrrrszProcess.num_threadscCs |jjS)zReturn threads opened by process as a list of (id, user_time, system_time) namedtuples representing thread id and thread CPU times (user/system). )rthreads)rqrrrrszProcess.threadsc Csttdrtj}nd}g}|s|dkr|xtD]F}y,|j|jkr^|j|jkr^|j|Wq0tk rtYq0Xq0Wn\xZ|j D]N\}}||jkry&t |}|j|jkr|j|Wqtk rYqXqWnt t }|dkr.xtD]2}y||jj|Wqtk r&YqXqWnJxH|j D]<\}}yt |}||j|Wntk rpYnXq8W|jg} xv| D]n}xf||D]Z}y|j|jk} Wntk rYn*X| r|j||j| kr| j|jqWqW|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. ppid_mapN) rrrr+rrmrappendr itemsr'r>list) rq recursiverrprmrZchildtableZ checkpidsZintimerrrrs\            zProcess.childrenc s|dk o|dk}ttr(fdd}ndd}|r`|}|jj}tj||}|jj}n<|j}|j}|}|jj}|dks|dkr||_||_dS|j|j|j |j }||} ||_||_y|| d} Wnt k rdSXt | dSdS)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. 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 >>> Ngcs tS)N)_timerr)num_cpusrrBsz%Process.cpu_percent..cSs ttS)N)sumr/rrrrrDsdr) r2rrr/timesleeprrusersystemZeroDivisionErrorround) rqintervalblockingZtimerZst1Zpt1Zst2Zpt2Z delta_procZ delta_timeZoverall_percentr)rrr0$s8    zProcess.cpu_percentcCs |jjS)zReturn a (user, system) namedtuple representing the accumulated process time, in seconds. This is the same as os.times() but per-process. )rr/)rqrrrr/iszProcess.cpu_timescCs |jjS)aReturn a tuple representing RSS (Resident Set Size) and VMS (Virtual Memory Size) in bytes. On UNIX RSS and VMS are the same values shown by 'ps'. On Windows RSS and VMS refer to "Mem Usage" and "VM Size" columns of taskmgr.exe. )r memory_info)rqrrrrps zProcess.memory_infocCs |jjS)zReturn a namedtuple with variable fields depending on the platform representing extended memory information about this process. All numbers are expressed in bytes. )rmemory_info_ex)rqrrrr{szProcess.memory_info_exc CsD|jjd}tptj}y|t|dStk r>dSXdS)zCompare physical system memory to process resident memory (RSS) and calculate process memory utilization as a percentage. rrgN)rr _TOTAL_PHYMEMr-totalfloatr)rqrssZ total_phymemrrrmemory_percents  zProcess.memory_percentTc s|jj}|rixZ|D]R}|d}|dd}ytdd|||<Wqtk rh||<YqXqWtjfddDStjfdd|DSdS) aReturn process' mapped memory regions as a list of nameduples 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'). rNcSs||S)Nr)ryrrrrsz%Process.memory_maps..csg|]}|f|qSrr)rr)drfrrrsz'Process.memory_maps..csg|] }|qSrr)rr)rfrrrs)r memory_mapsmapKeyErrorrZ pmmap_groupedZ pmmap_ext)rqZgroupeditZtuplrnumsr)rrfrrs   zProcess.memory_mapscCs |jjS)zReturn files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. )r open_files)rqrrrr szProcess.open_filesinetcCs |jj|S)aReturn 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)rqkindrrrr szProcess.connectionsc Cstytj|j|Wn\tk rntjd}|jtjkrNd|_t |j|j |jtj krht |j|j YnXdS)NrT) rrrmOSErrorrrerrnoZESRCHrr rwZEPERMr )rqsigrrrr _send_signals   zProcess._send_signalcCs2tr|j|n|tjkr&|jjntddS)zSend a signal 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(). z$only SIGTERM is supported on WindowsN)rrsignalSIGTERMrrr)rqrrrrrs    zProcess.send_signalcCs tr|jtjn |jjdS)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)rrrSIGSTOPrr)rqrrrrszProcess.suspendcCs tr|jtjn |jjdS)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)rrrSIGCONTrr)rqrrrrszProcess.resumecCs tr|jtjn |jjdS)zTerminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)rrrrrr)rqrrrrszProcess.terminatecCs tr|jtjn |jjdS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)rrrSIGKILLrr)rqrrrrsz Process.killcCs&|dk r|dk rtd|jj|S)aWait for process to terminate and, if process is a children of os.getpid(), also return its exit code, else None. 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)rrr)rqtimeoutrrrr s z Process.waitr) replacementcCsdS)Nr)rqrrr get_children szProcess.get_childrenr cCsdS)Nr)rqrrrget_connections$szProcess.get_connectionsrcCsdS)Nr)rqrrrget_cpu_affinity)szProcess.get_cpu_affinitycCsdS)Nr)rqrrrrset_cpu_affinity-szProcess.set_cpu_affinityr0cCsdS)Nr)rqrrrget_cpu_percent1szProcess.get_cpu_percentr/cCsdS)Nr)rqrrr get_cpu_times5szProcess.get_cpu_timesrcCsdS)Nr)rqrrrr9szProcess.getcwdrcCsdS)Nr)rqrrrget_ext_memory_info=szProcess.get_ext_memory_infocCsdS)Nr)rqrrrget_io_countersBszProcess.get_io_countersrcCsdS)Nr)rqrrr get_ioniceGszProcess.get_ionicecCsdS)Nr)rqrrrrr set_ioniceKszProcess.set_ionicercCsdS)Nr)rqrrrget_memory_infoOszProcess.get_memory_inforcCsdS)Nr)rqrrrget_memory_mapsSszProcess.get_memory_mapsrcCsdS)Nr)rqrrrget_memory_percentWszProcess.get_memory_percentrcCsdS)Nr)rqrrrget_nice[szProcess.get_nicercCsdS)Nr)rqrrrget_num_ctx_switches_szProcess.get_num_ctx_switchesrcCsdS)Nr)rqrrr get_num_fdsdszProcess.get_num_fdsrcCsdS)Nr)rqrrrget_num_handlesiszProcess.get_num_handlesrcCsdS)Nr)rqrrrget_num_threadsmszProcess.get_num_threadsr cCsdS)Nr)rqrrrget_open_filesqszProcess.get_open_filescCsdS)Nr)rqrrr get_rlimitvszProcess.get_rlimitcCsdS)Nr)rqrrrrr set_rlimitzszProcess.set_rlimitrcCsdS)Nr)rqrrr get_threads~szProcess.get_threadscCsdS)Nr)rqrrrrset_niceszProcess.set_nice)N)F)N)NN)N)N)F)N)T)r )N)N)Wrhrirjrkrlr~rsrrrrrrrvr;rmrrnrrrrrrrrrrrrrrr'rrrr_WINDOWSrrrrr}rr0r/rrrrr r rrrrrrrrlocalsZ_locals_deprecated_methodrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/rrrrr's  * 8 (         _ E             cs:eZdZdZddZddZddZd fd d ZZS) r(atA more convenient interface to stdlib subprocess module. It starts a sub process and deals with it exactly as when using subprocess.Popen class but in addition also provides all the properties and methods of psutil.Process class as a unified interface: >>> 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 >>> For method names common to both classes such as kill(), terminate() and wait(), psutil.Process implementation takes precedence. Unlike subprocess.Popen this class pre-emptively checks wheter PID has been reused on send_signal(), terminate() and kill() so that you don't accidentally terminate another process, fixing http://bugs.python.org/issue6973. For a complete documentation refer to: http://docs.python.org/library/subprocess.html cOs$tj|||_|j|jjdddS)NT)r) subprocessr(_Popen__subprocr~rm)rqrxryrrrrlszPopen.__init__cCsttttttjS)N)sortedrrr(r3)rqrrr__dir__sz Popen.__dir__cCs^y tj||Stk rXytj|j|Stk rRtd|jj|fYnXYnXdS)Nz!%s instance has no attribute '%s')object__getattribute__AttributeErrorr4rrh)rqrnrrrr8s zPopen.__getattribute__Ncs0|jjdk r|jjStt|j|}||j_|S)N)r4 returncodesuperr(r)rqrr)rrrrs  z Popen.wait)N) rhrirjrkrlr6r8r __classcell__rr)rrr(s ! cCstjS)z&Return a list of current running PIDs.)rr*rrrrr*scCs0|dkr dS|dkr"tr"|tkStj|SdS)zReturn True if given PID exists in the current process list. This is faster than doing "pid in psutil.pids()" and should be preferred. rFN)rr*rr))rmrrrr)s   c csdd}dd}tt}ttj}||}||}x|D] }||q.addcSstj|ddS)N)r=pop)rmrrrremoveszprocess_iter..removeN) rr*r=keysr5rrrfromkeysrvr r )r?rAabZnew_pidsZ gone_pidsrmr>rrrr+s(      c sfdd}|dk r0|dk r0d|}t|tt|}dk r\t r\tdt|dk rnt|}xt|r|dk r|dkrPxP|D]H}dt|}|dk rt|t|}|dkrP|||q|||qW|}qpW|r x|D]}||dqW|}tt|fS)aConvenience 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. 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\y|j|d}Wntk r$Yn4X|dk s8|j rX||_j|dk rX|dS)N)r)rr rvr:r?)r>rr:)callbackgonerr check_gone>s zwait_procs..check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg?)rrr<rrrminr) ZprocsrrFrHroaliveZdeadliner>Z max_timeoutr)rFrGrr,s6"        TcCs|r tjStjSdS)asReturn 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 (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() N)rZcpu_count_logicalZcpu_count_physical)Zlogicalrrrr2vsFcCs|s tjStjSdS)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 nameduples 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)rr/Z per_cpu_times)percpurrrr/s)rKcCs|dk o|dk}dd}|sF|r2t}tj|nt}ta||tSg}|rdtdd}tj|nt}tddax&t|tD]\}}|j|||q~W|SdS)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 >>> Ngc SsVt|}||j}t|}||j}||kr0dS||}||}||d}t|dS)Ngrr)rZidler) t1t2Zt1_allZt1_busyZt2_allZt2_busyZ busy_delta all_deltaZ busy_percrrr calculates   zcpu_percent..calculateT)rK)r/rr_last_cpu_times_last_per_cpu_timeszipr)rrKrrOrLrtot1rMrrrr0s$%     cCs|dk o|dk}dd}|sF|r2t}tj|nt}ta||tSg}|rdtdd}tj|nt}tddax&t|tD]\}}|j|||q~W|SdS)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(). Ngc Ssg}t|t|}x~|jD]t}t||t||}yd||}Wntk r\d}YnXt|d}tr|dkrzd}n |dkrd}|j|qWtj|S)NrgrgY@) r_fieldsrrrr0rrZ scputimes)rLrMr rNfieldZ field_deltaZ field_percrrrrOs     z$cpu_times_percent..calculateT)rK)r/rr_last_cpu_times_2_last_per_cpu_times_2rRr)rrKrrOrLrrSrMrrrr1s$     cCstj}|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 actual amount of available memory that can be given instantly to processes that request more memory in bytes; this is calculated by summing different memory values depending on the platform (e.g. free + buffers + cached on Linux) 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: OSX: active + inactive + 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, OSX): cache for various things. - wired (OSX, 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. )rr-rr)rrrrr-Hs6cCstjS)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. )rr.rrrrr.s cCs 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. )rr7)rrrrr7scCs 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. )rr6)allrrrr6s cCs\tj}|std|r>x |jD]\}}t|||<q"W|Stddt|jDSdS)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 milliseconds) - write_time: time spent writing to disk (in milliseconds) 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 namedutuple described above as the values. On recent Windows versions 'diskperf -y' command may need to be executed first otherwise this function won't find any disk. zcouldn't find any physical diskcSsg|] }t|qSr)r)rrrrrrsz$disk_io_counters..N)rr5 RuntimeErrorr_nt_sys_diskiorRvalues)ZperdiskrawdictZdiskfieldsrrrr5scCs\tj}|std|r>x |jD]\}}t|||<q"W|Stddt|jDSdS)a Return 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 OSX 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. z#couldn't find any network interfacecSsg|] }t|qSr)r)rrrrrrsz#net_io_counters..N)rr3rYr _nt_sys_netiorRr[)pernicr\Znicr]rrrr3sr cCs tj|S)aReturn system-wide 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 )rr4)r rrrr4scCstjS)zvReturn the system boot time expressed in seconds since the epoch. This is also available as psutil.BOOT_TIME. )rr9rrrrr9 scCstjS)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. )rr8rrrrr8s z psutil.pids())rcCstS)N)r*rrrr get_pid_list#sr`zlist(process_iter())cCs ttS)N)rr+rrrrget_process_list(srazpsutil.users()cCstS)N)r8rrrr get_users-srbzpsutil.virtual_memory()cCstS)zReturn the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated; use psutil.virtual_memory() instead. )r-rrrr phymem_usage2srczpsutil.swap_memory()cCstS)N)r.rrrr virtmem_usage;srdzpsutil.phymem_usage().freecCstjS)N)rcfreerrrr avail_phymem@srfzpsutil.phymem_usage().usedcCstjS)N)rcusedrrrr used_phymemEsrhzpsutil.virtmem_usage().totalcCstjS)N)rdrrrrr total_virtmemJsrizpsutil.virtmem_usage().usedcCstjS)N)rdrgrrrr used_virtmemOsrjzpsutil.virtmem_usage().freecCstjS)N)rdrerrrr avail_virtmemTsrkzpsutil.net_io_counters()cCst|S)N)r3)r_rrrnetwork_io_countersYsrlc Cs"ddl}ddlm}|jj}d}ddddd d d g}trL|jd |jd ||d"xtD]}y|j|dd}Wnt k rYqbX|d r|jj |d }|j|kr|j d}q|j d}nd}t j dt j t|d }y |j} WnVtk r4tr.|d r(t|d j} nd} nYntk rLd} YnXtrld| krl| jdd} |d rt|d jdpd } |d rt|d jdpd } |drt|ddpd } ||| dd!|d|d| | | |jd dpd |||djpd f qbWdS)#zNList info of all currently running processes emulating ps aux output. rN)print_z+%-10s %5s %4s %4s %7s %7s %-13s %5s %7s %srmr0rrnr/rrrrUSERPID%CPU%MEMVSZRSSTTYSTARTTIMECOMMANDrt)rz%H:%Mz%b%dz%M:%S\ri? ) rnrorprqrrrsrtrurvrw)datetimepsutil._compatrmdatetodayrrr+rr fromtimestampstrftimer localtimerrrstrrr r0splitrvmsrrrstrip) r{rmZ today_dayZtemplrrZpinfoctimeZcputimerrrZmemprrrtest^sh              rcCs8Gdddt}|}t|_tjt|_|tjt<dS)zDirty hack to replace the module object in order to access deprecated module constants, see: http://www.dr-josiah.com/2013/12/properties-on-python-modules.html c@s<eZdZddZeZeddZeddZeddZd S) z&_replace_module..ModuleWrappercSs t|jS)N)rp_module)rqrrrrsz/_replace_module..ModuleWrapper.__repr__cSsd}tj|tddtS)Nz8NUM_CPUS constant is deprecated; use cpu_count() insteadr)rr)rrrr2)rqrorrrNUM_CPUSsz/_replace_module..ModuleWrapper.NUM_CPUScSsd}tj|tddtS)Nz9BOOT_TIME constant is deprecated; use boot_time() insteadr)rr)rrrr9)rqrorrr BOOT_TIMEsz0_replace_module..ModuleWrapper.BOOT_TIMEcSsd}tj|tddtjS)NzGTOTAL_PHYMEM constant is deprecated; use virtual_memory().total insteadr)rr)rrrr-r)rqrorrr TOTAL_PHYMEMsz3_replace_module..ModuleWrapper.TOTAL_PHYMEMN) rhrirjrrsr;rrrrrrr ModuleWrappers   rN)r7globals__dict__rmodulesrhr)rmodrrr_replace_modules  rr__main__)NN)T)F)NF)NF)F)F)F)r )F)rr)rkZ __future__r __author__rtuplerr__all__rrrrrrr3rrZpsutil._commonr:r|r;r<r=r>r?r|r@rrAr2rBZ _deprecatedrCrZrDr^rrrrrrrrrrrrrrrrr r!r"r#r$r%r&platformrZpsutil._pslinuxZ_pslinuxrrFrGrHrIrJrKZ HAS_PRLIMITZ _psutil_linuxrLrMrNrOrPrQrRrSrTrUrVrWZRLIMIT_MSGQUEUEr9Z RLIMIT_NICEZ RLIMIT_RTPRIOZ RLIMIT_RTTIMEZRLIMIT_SIGPENDINGZpsutil._pswindowsZ _pswindowsZ_psutil_windowsrYrZr[r\r]r^r_Z psutil._psosxZ_psosxZ psutil._psbsdZ_psbsdZpsutil._pssunosZ_pssunosrcrdrextendZ__extra__all__rrnrr0rr Exceptionr r r r r}r7r'r(r*r)r=r+r,r2r/rPrQr0rVrWr1r-r.r7r6r5r3r4r9r8r`rarbrcrdrfrhrirjrkrlrrrrhrrrr s    8 8  8              C2 Z    Q J< "     @$