3 ̪eQ\O@s" dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z y ddl Z Wnek rdZ YnXddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm 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$lm/Z/dd%lm0Z0dd&lm1Z1dd'lm2Z2dd(lm3Z3dd)lm4Z4dd*lm5Z5dd+lm6Z6dd,lm7Z7dd-lm8Z8dd.lm9Z9dd/lm:Z:dd0lm;Z;dd1lmZ>dd4lm?Z@dd5lAmBZCdd6lAmDZDdd7lAmEZEdd8lAmFZGdd9lAmHZHe rLd:ZIdd;lmJZKddlJmNZNdd?lJmOZOne8rdd@lmPZKddAlQmRZRddBlQmSZSddClQmTZTddDlQmUZUddElQmVZVddFlQmWZWddGlPmXZXddHlPmYZYddIlPmZZZddJlPm[Z[ddKlPm\Z\n~e!rddLlm]ZKnjer ddMlm^ZKnVe7r[e jxddk r[[edk redS)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 Works with Python versions 2.7 and 3.6+. )divisionN)_common)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)memoize_when_activated) wrap_numbers)PY3)PermissionError)ProcessLookupError)SubprocessTimeoutExpired)longz/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)_psaixzplatform %s is not supportedr.r/r1r-r0 version_info __version__r$r!r%r r&r'r*rr)r"r(r#r rrr r rrrr rr 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_timerlimit) _psutil_posixZRLIMzGiampaolo Rodola'z5.9.8cCsg|] }t|qS)int).0numrkrk;/usr/local/lib64/python3.6/site-packages/psutil/__init__.py srp. monotonicversionz!version conflict: %r C extension z.module was built for another version of psutilz (%s instead of %s)cCsg|]}|qSrkrk)rmxrkrkrorpsz (different than %s)z;; you may try to 'pip uninstall psutil', manually remove %s__file__z%the existing psutil install directoryz1 or clean the virtual env somehow, then reinstallppid_mapc CsHi}x>tD]4}ytj|j||<Wq ttfk r>Yq Xq W|S)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )rV _psplatformrSppidr/r1)retpidrkrkro _ppid_maps  r|cCs6tj}t||}|dkr dnd}tjj|j|S)z(Format seconds in a human readable form.<z%H:%M:%Sz%Y-%m-%d %H:%M:%SiiQ)timerldatetime fromtimestampstrftime)ZsecsnowZsecs_agofmtrkrkro _pprint_secss rc@s~eZdZdZd{ddZd|ddZdd ZeZd d Zd d Z ddZ ddZ e ddZ ejddZd}ddZddZddZddZeddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd~d.d/Zered0d1Z d2d3Z!d4d5Z"d6d7Z#e$e%j&d8rd9d:Z'e$e%j&d;r.ddrFdd?d@Z)e$e%j&dAr^ddBdCZ*e$e%j&dDrtdEdFZ+e$e%j&dGrdHdIZ,e-rdJdKZ.dLdMZ/dNdOZ0e$e%j&dPrdQdRZ1ddSdTZ2ddUdVZ3edWdXZ4edYdZZ5e6j7d[d\d]d^Z8d_d`Z9ddbdcZ:e$e%j&ddr(ddfdgZ;dhdiZdodpZ?dqdrZ@dsdtZAdudvZBdwdxZCddydzZDdS)rSa)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)selfr{rkrkro__init__BszProcess.__init__FcCs^|dkrtj}nxt r8t|ttf r8d|}t||dkrPd|}t|ytj j |Wn(t k rd|}t ||dYnX||_ d|_d|_d|_d|_d|_d|_tj|_d|_tj||_d|_d|_t|_y |jWn\tk rYnHt k rYn4t k rJ|s@d}t ||dnd|_YnX|j!|jf|_"dS) Nzpid must be an integer (got %r)rz'pid must be a positive integer (got %s)z!process PID out of range (got %s))msgFzprocess PID not foundT)#osgetpid_PY3 isinstancerlr8 TypeError ValueErrorrxcextZcheck_pid_range OverflowErrorr/_pid_name_exe _create_time_gone _pid_reused_hash threadingRLock_lock_ppidrS_proc_last_sys_cpu_times_last_proc_cpu_times _SENTINEL _exitcode create_timer-r1r{_ident)rr{ _ignore_nsprrkrkrorEsL     z Process._initcCstj}|j|d<|jr"|j|d<|jy|j|d<|j|d<WnHtk rdd|d<Yn.tk r~d|d<Ynt k rYnX|j t dfkr|j |d<|j dk rt |j |d<d|jj|jjd jd d |jDfSQRXdS) Nr{namestatuszombieZ terminatedexitcodestartedz %s.%s(%s)z, cSsg|]\}}d||fqS)z%s=%rrk)rmkvrkrkrorpsz#Process.__str__..) collections OrderedDictr{roneshotrrr1r/r-rrrr __class__ __module____name__joinitems)rinforkrkro__str__}s,        zProcess.__str__c Csjt|tstStstr^|j\}}|j\}}||kr^|r^| r^y |jtkStk r\YnX|j|jkS)N) rrSNotImplementedrrrrr*r.)rotherZpid1Zctime1Zpid2Zctime2rkrkro__eq__s     zProcess.__eq__cCs ||k S)Nrk)rrrkrkro__ne__szProcess.__ne__cCs|jdkrt|j|_|jS)N)rhashr)rrkrkro__hash__s  zProcess.__hash__cCs*|j r&|jr&d}t|j|j|ddS)z9Raises NoSuchProcess in case process PID has been reused.z4process no longer exists and its PID has been reused)rN) is_runningrr/r{r)rrrkrkro_raise_if_pid_reusedszProcess._raise_if_pid_reusedcCs|jS)zThe process PID.)r)rrkrkror{sz Process.pidccs|jt|drdVnzH|jj||jj||jj|trP|jj||jj dVWd|jj ||jj ||jj |tr|jj ||jj XWdQRXdS)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_inforyruidsrZ oneshot_entercache_deactivateZ oneshot_exit)rrkrkrors"           zProcess.oneshotc Cs t}|dk rvt|ttttfs2dt|}t|t|}||}|rvdt|dkrXdnddj t t |f}t |i}|p|}|j xxp|D]h}y$|dkr|j} nt||} | } Wn6ttfk r|} Yntk r|rwYnX| ||<qWWdQRX|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 name%s %srsrsz, r{)_as_dict_attrnamesrlisttupleset frozensettyperlenrmapreprrrr{getattrr-r1NotImplementedError) rattrsad_valueZ valid_namesr invalid_namesZretdictlsrrzmethrkrkroas_dict s:      zProcess.as_dictc Csrtdk r tntd}|j|kr$dS|j}|dk rn|j}yt|}|j|krV|SWntk rlYnXdS)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_PIDrVr{ryrrSr/)rZ lowest_pidryctimeparentrkrkror:s  zProcess.parentcCs0g}|j}x|dk r*|j||j}qW|S)zReturn the parents of this process as a list of Process instances. If no parents are known return an empty list. N)rappend)rparentsprocrkrkrorMs    zProcess.parentsc CsZ|js |jrdSy|t|jk|_|j Stk r<dStk rTd|_dSXdS)zReturn whether this process is running. It also checks if PID has been reused by another process in which case return False. FTN)rrrSr{r1r/)rrkrkrorXs zProcess.is_runningcCs2|jtr|jjS|jp$|jj|_|jSdS)z`The process parent PID. On Windows the return value is cached after first call. N)rrrryr)rrkrkroryqs  z Process.ppidc Cstr|jdk r|jS|jj}trvt|dkrvy |j}Wnttfk rRYn$X|rvt j j |d}|j |rv|}||_||j_|S)z>The process name. The return value is cached after first call.Nr) r,rrrrrcmdliner-r1rpathbasename startswith)rrrZ extended_namerkrkrors   z Process.namecsfdd}jdkrzyjj}Wn&tk rJ}z ||dSd}~Xn0X|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) rrrrisabsisfilerrrr-)fallbackrexe)rrkroguess_its   zProcess.exe..guess_itN)r)rrrr-)rrrerrrk)rrors  z Process.execCs |jjS)z3The command line this process has been called with.)rr)rrkrkrorszProcess.cmdlinec Cs$y |jjStk rtSXdS)z2The process current status as a STATUS_* constant.N)rrr1r*)rrkrkrors zProcess.statusc CsXtrJtdkrd}t||jj}y tj|jStk rFt|SXn |j j SdS)ztThe name of the user that owns the process. On UNIX this is calculated by using *real* process uid. Nz0requires pwd module shipped with standard python) rpwd ImportErrorrrealgetpwuidpw_nameKeyErrorstrrusername)rrZreal_uidrkrkrors   zProcess.usernamecCs|jdkr|jj|_|jS)zThe process creation time as a floating point number expressed in seconds since the epoch. The return value is cached after first call. N)rrr)rrkrkrors  zProcess.create_timecCs |jjS)z6Process current working directory as an absolute path.)rcwd)rrkrkrorsz Process.cwdcCs*|dkr|jjS|j|jj|dS)z'Get or set process niceness (priority).N)rZnice_getrZnice_set)rvaluerkrkronices z Process.nicecCs |jjS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rr)rrkrkrorsz Process.uidscCs |jjS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgids)rrkrkrorsz Process.gidscCs |jjS)zVThe terminal associated with this process, if any, else None. )rterminal)rrkrkrorszProcess.terminalcCs |jjS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fds)rrkrkrorszProcess.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)rrkrkrorszProcess.io_counters ionice_getcCs@|dkr&|dk rd}t||jjS|j|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' argument must be specified)rrrrZ ionice_set)rioclassrrrkrkroionice)s  zProcess.ionicericCs|dk r|j|jj||S)a-Get or set process resource limits as a (soft, hard) tuple. *resource* is one of the RLIMIT_* constants. *limits* is supposed to be a (soft, hard) tuple. See "man prlimit" for further info. Available on Linux and FreeBSD only. N)rrri)rresourceZlimitsrkrkroriAs zProcess.rlimitcpu_affinity_getcCsl|dkrtt|jjS|j|sTt|jdr>|jj}nttt t dd}|jj t t|dS)a-Get or set process CPU affinity. If specified, *cpus* must be a list of CPUs for which you want to set the affinity (e.g. [0, 1]). If an empty list is passed, all egible CPUs are assumed (and set). (Windows, Linux and BSD only). N_get_eligible_cpusT)percpu) sortedrrrrrrrrangerr[Zcpu_affinity_setr)rZcpusrkrkro cpu_affinityRs  zProcess.cpu_affinitycpu_numcCs |jjS)aZReturn what CPU this process is currently running on. The returned number should be <= psutil.cpu_count() and <= len(psutil.cpu_percent(percpu=True)). It may be used in conjunction with psutil.cpu_percent(percpu=True) to observe the system workload distributed across CPUs. )rr)rrkrkrorhszProcess.cpu_numenvironcCs |jjS)zThe environment variables of the process as a dict. Note: this might not reflect changes made after the process started. )rr)rrkrkroruszProcess.environcCs |jjS)z\Return the number of handles opened by this process (Windows only). )r num_handles)rrkrkror}szProcess.num_handlescCs |jjS)zkReturn the number of voluntary and involuntary context switches performed by this process. )rnum_ctx_switches)rrkrkrorszProcess.num_ctx_switchescCs |jjS)z2Return the number of threads used by this process.)r num_threads)rrkrkrorszProcess.num_threadsthreadscCs |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). On OpenBSD this method requires root access. )rr)rrkrkrorszProcess.threadsc CsD|jt}g}|sxx^|jD]R\}}||jkr y&t|}|j|jkrV|j|Wq ttfk rpYq Xq Wnt j t }x"|jD]\}}||j|qWt }|jg} x| r>| j }||krq|j|xb||D]V} y6t| }|j|jk} | r|j|| j| Wqttfk r6YqXqWqW|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. )rr|rr{rSrrr/r1r defaultdictrrpopadd) r recursiverwrzr{rychildZreverse_ppid_mapseenstackZ child_pidZintimerkrkrochildrens@     zProcess.childrenc s|dk o|dk}|dk r0|dkr0d|}t|tp8dfdd}|rv|}|jj}tj||}|jj}n<|j}|j}|}|jj}|dks|dkr||_||_dS|j|j|j |j } ||} ||_||_y| | d} Wnt k rdSX| } t | 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. 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 >>> Ngrz!interval is not positive (got %r)rcs tS)N)_timerrk)num_cpusrkrotimersz"Process.cpu_percent..timerd) rr^rr[rsleeprrusersystemZeroDivisionErrorround) rintervalblockingrrZst1Zpt1Zst2Zpt2Z delta_procZ delta_timeZoverall_cpus_percentZsingle_cpu_percentrk)rror\s<#      zProcess.cpu_percentcCs |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. )rr[)rrkrkror[:s zProcess.cpu_timescCs |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. )rr)rrkrkrorEs zProcess.memory_infor) replacementcCs|jS)N)r)rrkrkromemory_info_exPszProcess.memory_info_excCs |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_info)rrkrkrorTszProcess.memory_full_inforsscCsttjj}||kr,d|t|f}t||tjjkr>|jn|j}|}t ||}t p^t j }|dksxd|}t||t |dS)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') z&invalid memtype %r; valid types are %rrz`can't calculate process memory percent because total physical system memory is not positive (%r)r)rrxZpfullmem_fieldsrrZpmemrrr _TOTAL_PHYMEMrYtotalfloat)rZmemtypeZ valid_typesrfunmetricsrZ total_phymemrkrkromemory_percentds    zProcess.memory_percent memory_mapsTc s|jj}|rixZ|D]R}|d}|dd}ytdd|||<Wqtk rh||<YqXqWtjfddDStjfdd|DSdS) 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'). NcSs||S)Nrk)ruyrkrkrosz%Process.memory_maps..csg|]}|f|qSrkrk)rmr)dntrkrorpsz'Process.memory_maps..csg|] }|qSrkrk)rmru)r,rkrorps)rr&rrrxZ pmmap_groupedZ pmmap_ext)rZgroupeditZtuplrnumsrk)r+r,ror&s   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)rrkrkror/szProcess.open_filesinetcCs |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 | +------------+----------------------------------------------------+ )r connections)rkindrkrkror1szProcess.connectionsc Cs|jdk st|j|j|jdkr4d}t|ytj|j|Wnjtk rtrxt|jrxt |j|j |j nd|_ t |j|j Yn"tk rt|j|j YnXdS)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{AssertionErrorrrrkillr6rrUr1rrrr/r5r-)rsigrrkrkro _send_signals zProcess._send_signalcCsRtr|j|n>|j|tjkrB|j rBd}t|j|j|d|j 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(). zprocess no longer exists)rN) rr6rsignalSIGTERMrr/r{rr send_signal)rr5rrkrkror9s zProcess.send_signalcCs(tr|jtjn|j|jjdS)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)rr6r7SIGSTOPrrsuspend)rrkrkror;szProcess.suspendcCs(tr|jtjn|j|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)rr6r7SIGCONTrrresume)rrkrkror=szProcess.resumecCs(tr|jtjn|j|jjdS)zTerminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)rr6r7r8rrr4)rrkrkro terminateszProcess.terminatecCs(tr|jtjn|j|jjdS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)rr6r7SIGKILLrrr4)rrkrkror4sz Process.killcCsB|dk r|dk rd}t||jtk r.|jS|jj||_|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)rtimeoutrrkrkror@s z Process.wait)N)F)NN)N)NN)N)N)F)N)r)T)r0)N)Err __qualname____doc__rrr__repr__rrrrpropertyr{ contextlibcontextmanagerrrrrrr2ryrrrrrrrrrrrrrrrxrSrrrirrrr,rrrrrr\r[rrdeprecated_methodrrr%r&r/r1r6r9r;r=r>r4r@rkrkrkrorS!s  8 C /  *         F ]  $      cCs$g|]}|jd r|dkr|qS)_r9r;r=r>r4r@rrrrrrirr>rir9rrr@rrr>rrr4rr;r=)r)rmrurkrkrorp4scsJeZdZdZddZddZddZdd Zd d Zdfd d Z Z S)rTaSame as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence: * send_signal() * terminate() * kill() This is done in order to avoid killing another process in case its PID has been reused, fixing BPO-6973. >>> import psutil >>> from subprocess import PIPE >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE) >>> p.name() 'python' >>> p.uids() user(real=1000, effective=1000, saved=1000) >>> p.username() 'giampaolo' >>> p.communicate() ('hi', None) >>> p.terminate() >>> p.wait(timeout=2) 0 >>> cOs$tj|||_|j|jjdddS)NT)r) subprocessrT_Popen__subprocrr{)rargskwargsrkrkror^szPopen.__init__cCsttttttjS)N)rrdirrTrJ)rrkrkro__dir__esz Popen.__dir__cCst|jdr|jj|S)N __enter__)rrKrP)rrkrkrorPhs  zPopen.__enter__c Os^t|jdr|jj||S|jr*|jj|jr:|jjz|jrL|jjWd|jXdS)N__exit__)rrKrQstdoutclosestderrstdinr@)rrLrMrkrkrorQms   zPopen.__exit__cCsby tj||Stk r\ytj|j|Stk rVd|jj|f}t|YnXYnXdS)Nz!%s instance has no attribute '%s')object__getattribute__AttributeErrorrKrr)rrrrkrkrorW}s zPopen.__getattribute__Ncs0|jjdk r|jjStt|j|}||j_|S)N)rK returncodesuperrTr@)rrArz)rrkror@s  z Popen.wait)N) rrrBrCrrOrPrQrWr@ __classcell__rkrk)rrorT@s cCsttj}|da|S)z&Return a list of current running PIDs.r)rrxrVr)rzrkrkrorVs cCs0|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)rrVrxrU)r{rkrkrorUs   c #s^fdd}fdd}tjtt}tj}||}||}x|D] }||qPWzttjttj |j} x| D]\}} yJ| dkr||Vn2| j rЈdk r| j d| _ | Vn ||VWqt k r||Yqtk rJ| dkrD|krDy|VWntk r@YnXnYqXqWWdaXdS)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). cs.t|}dk r |jd|_||j<|S)N)rr)rSrrr{)r{r)rrpmaprkror s  zprocess_iter..addcsj|ddS)N)r )r{)r\rkroremoveszprocess_iter..removeN)rr)_pmapcopyrrVkeysrrrdictfromkeysrrrr/r-r) rrr r]abZnew_pidsZ gone_pidsr{rrrk)rrr\rorWs>     "   c sfdd}|dk r0|dk r0d|}t|tt|}dk r`t r`d}t||dk rrt|}xt|r|dk r|dkrPxP|D]H}dt|}|dk rt|t|}|dkrP|||q|||qW|}qtW|rx|D]}||dqW|}tt|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 sny|j|d}Wn&tk r$YnFtk r6Yn4X|dk sJ|j rj||_j|dk rj|dS)N)rA)r@r0_SubprocessTimeoutExpiredrrYr )rrArY)callbackgonerkro check_gone&s zwait_procs..check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg?)rrcallablerrrminr) ZprocsrArfrhralivedeadlinerZ max_timeoutrk)rfrgrorXs8%      TcCs.|rtj}ntj}|dk r*|dkr*d}|S)azReturn the number of logical CPUs in the system (same as os.cpu_count() in Python 3.4). If *logical* is False return the number of physical cores only (e.g. hyper thread CPUs are excluded). Return None if undetermined. The return value is cached after first call. If desired cache can be cleared like this: >>> psutil.cpu_count.cache_clear() Nr)rxZcpu_count_logicalZcpu_count_cores)Zlogicalrzrkrkror^cs  FcCs|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 namedtuples for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. N)rxr[Z per_cpu_times)rrkrkror[zs)rcCs0t|}tr,|t|dd8}|t|dd8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). ZguestrZ guest_nice)sumrr)timesZtotrkrkro _cpu_tot_times  rocCs&t|}||j8}|t|dd8}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time. We do so by subtracting all idle CPU times. Ziowaitr)roidler)rnZbusyrkrkro_cpu_busy_times rqcCs`|j|jkst||fg}x8tjjD],}t||t||}td|}|j|q&Wtj|S)Nr)rr3rx scputimesrmaxr)t1t2Z field_deltasfield field_deltarkrkro_cpu_times_deltass rxc Cstjj}|dk o|dk}|dk r:|dkr:d|}t|dd}|s|r\t}tj|ntj|pjt}tt|<||t|Sg}|rtdd}tj|nt j|ptdd}tddt |<x*t |t |D]\}} |j ||| qW|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 >>> Ngrz!interval is not positive (got %r)c SsNt||}t|}t|}y||d}Wntk r>dSXt|dSdS)Nrgr)rxrorqrr)rtru times_delta all_deltaZ busy_deltaZ busy_percrkrkro calculates zcpu_percent..calculateT)r) rcurrent_threadidentrr[rr_last_cpu_timesget_last_per_cpu_timeszipr) rrtidrrr{rtrztot1rurkrkror\s,#      c Cstjj}|dk o|dk}|dk r:|dkr:d|}t|dd}|s|r\t}tj|ntj|pjt}tt|<||t|Sg}|rtdd}tj|nt j|ptdd}tddt |<x*t |t |D]\}} |j ||| qW|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(). Ngrz!interval is not positive (got %r)cSshg}t||}t|}dtd|}x8|D]0}||}t|d}ttd|d}|j|q*Wtj|S)NgY@rg)rxrorsrrjrrxrr)rtrur.ryrzZscalerwZ field_percrkrkror{Bs   z$cpu_times_percent..calculateT)r) rr|r}rr[rr_last_cpu_times_2r_last_per_cpu_times_2rr) rrrrrr{rtrzrrurkrkror]/s,     cCstjS)zReturn CPU statistics.)rxr_rkrkrkror_jscpu_freqc Cstj}|r|Stt|}|dkr(dS|dkr8|dSd\}}}d}x>|D]6}||j7}trn|jdkrnd}qL||j7}||j7}qLW||}|rd} } n||} ||} tj || | SdS)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. rNrFT)rrr) rxrr"rcurrentrrjrsrscpufreq) rrzrZcurrsZminsZmaxsZset_noneZcpurZmin_Zmax_rkrkrorqs.       getloadavgcCstj}|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. )rxrYr!r )rzrkrkrorYs5cCstjS)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. )rxrZrkrkrkrorZs 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. )rxrf)rrkrkrorfscCs\dd}tj|}trTg}x4|D],}|j||jd||jdd}|j|q W|S|SdS)a3Return mounted partitions as a list of (device, mountpoint, fstype, opts) namedtuple. 'opts' field is a raw string separated by commas indicating mount options which may vary depending on the platform. If *all* parameter is False return physical devices only and ignore all others. c Ss*y tj||Sttfk r$YnXdS)N)rpathconfOSErrorrX)rrrkrkrors z!disk_partitions..pathconf PC_NAME_MAX PC_PATH_MAX)maxfilemaxpathN)rxrer_replace mountpointr)allrrznewitemr,rkrkrores    cCstrt|dni}tjf|}|s.|r*iSdS|rNsz#disk_io_counters..) rrarxrd _wrap_numbersrrrrrvalues)rnowraprMrawdictr,Zdiskfieldsrkrkrord"s    zpsutil.disk_io_counterszClears nowrap argument cachecCsrtj}|s|riSdS|r&t|d}|rRx"|jD]\}}tj|||<q4W|Stjddt|jDSdS)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. Nzpsutil.net_io_counterscSsg|] }t|qSrk)rm)rmrurkrkrorpsz#net_io_counters..)rxr`rrrsnetiorr)ZpernicrrZnicrrkrkror`\s  zpsutil.net_io_countersr0cCs 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. )rxra)r2rkrkrorasc Cst}|rddl}tj}|jdddtjt}x|D]\}}}}}} |ry|j|}WnBt k rt r~|d kr~tj }nt tdr|tj krtj }YnX|tj krt rdnd } x|j| d kr|d | 7}qW||jtj||||| q8Wt|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. rNcSs|dS)Nrrk)rurkrkror*sznet_if_addrs..)keyrrR:-z%s00)rsocketrxrbsortrrr AddressFamilyrr,rRrrcountrrsnicaddrra) Z has_enumsrZrawlistrzrfamaddrmask broadcastptp separatorrkrkrorbs,        cCstjS)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. )rxrcrkrkrkrorcs sensors_temperaturesc sfdd}tjt}tj}x|jD]t\}}xj|r|jd\}}}} ||}||}|| } |rp| rp|} n| r~| r~| }||jtj |||| q2Wq(Wt |S)a<Return hardware temperatures. Each entry is a namedtuple representing a certain hardware sensor (it may be a CPU, an hard disk or something else, depending on the OS and its configuration). All temperatures are expressed in celsius unless *fahrenheit* is set to True. cs(|dk r$r t|dddS|SdS)N r )r")n) fahrenheitrkroconvertsz%sensors_temperatures..convertr) rrrrxrrr rrshwtempra) rrrzrrrlabelrhighcriticalrk)rrors     sensors_fanscCstjS)zReturn fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). )rxrrkrkrkror ssensors_batterycCstjS)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. )rxrrkrkrkror$ s cCstjS)zAReturn the system boot time expressed in seconds since the epoch.)rxrhrkrkrkrorh8 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. )rxrgrkrkrkrorg? s cCstjS)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )rxwin_service_iterrkrkrkrorS srcCs tj|S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )rxwin_service_get)rrkrkrorY srcCs(ddl}t||j_tjjt|dS)zZEnable or disable PSUTIL_DEBUG option, which prints debugging messages to stderr. rN)Zpsutil._commonboolr PSUTIL_DEBUGrxrZ set_debug)rpsutilrkrkro _set_debugc s rcCs^ddlm}ddlm}tjj}d}ddddd d d d d dg }t|d$x t|ddD]}|j d rtjj |j d }|j|kr|j d}q|j d}nd}|j d rt j dt j t|j d }nd}|j dpd}| otry|jd}Wntk rYnX|r6tr6d|kr6|jdd}|dd }|j d dk rb||j d jnd} |j d dk r||j d jnd} |j ddk rt|j ddnd} |j d rt|j d nd} |j drd!j|j d} n |j d} |j d r|j d dd"nd}||dd#|j d| | | | |||| f }t|d|dqZWdS)%Nr) bytes2human)get_terminal_sizez)%-10s %5s %5s %7s %7s %5s %6s %6s %6s %sr{r%rrr[rrrrrUSERPID%MEMVSZRSSNICESTATUSSTARTTIMECMDLINE)rz%H:%Mz%b%drsz%M:%Sr\r r ) rrrrrrrrrr)rr_compatrrdatetodayprintrWrrrr localtimermrrr.r,splitvmsrrrlr)rrZ today_dayZtemplrprZcputimerrrZmemprrrlinerkrkrotestm sf                " rr(__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r0)F)rC __future__rrrFr functoolsrr7rJsysrrrrrsrrrrrr r r r r rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3rrr4rr5r6r7rer8 PROCFS_PATHr9rxr:r;r<r=r>Z_psutil_windowsr?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrplatform__all__extendZ__extra__all__rrSrjglobalsZ_globalsrrNrisupperrrrR __author__rQrrrPrr rrVrrlreplacerrvrrrrtrwr|rrrrTrVrUr^rWrXr^r[r|r}r~ Exceptionrrorqrxr\r_rrr]r_rrrYrZrfrerdpartial cache_clearr`rarbrcrrrrhrgrrrrrnrurrkrkrkros                                                                                     W M b     N ;  (   ;  /  '  2  "       J