U =_RG@sdZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z z ddl Z Wnek rdZ YnXddlmZddlmZddlmZddlmZdd 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;lHmJZJddlHmMZMneFrdd?lmNZIdd@lOmPZPddAlOmQZQddBlOmRZRddClOmSZSddDlOmTZTddElOmUZUddFlNmVZVddGlNmWZWddHlNmXZXddIlNmYZYddJlNmZZZn~e@rddKlm[ZInje=rddLlm\ZInVeEr0ddMlm]ZIddNl]m^Z^ddOl]m_Z_d9ZGn&e<rHddPlm`ZId9ZGneadQe jbdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdbdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddgGZcecdeIjeefeIjgdrZddlmhZheiZjdZkelehD]4Zkekmdr eknr eoehekejek<ecpekq [j[keIjqZqdZrdZsetddesudDZveoe de j ZwdaxdayezZ{e|es}ddeoeIj~ddkr6deoeIj~dZefeIj~dreddddeeIj~jDesf7Zn edes7ZedeoeIj~dd7Zed7ZeeefeIdrJeIjZnddZddZddZGdddezZgeddelegDZGdddegZddZddZiZe ZdddZdddZdddZdddZz eaWnek rdaYnXzeddaWnek r*daYnXddZddZddÄZdddZtatadddZddZefeIdǃrdddDŽZecpdǡefedɃsefeIdɃrefedɃrejZneIjZecpdɡddZddZddZdddZdddZeejdϡe_dej_dddZeejdҡe_dej_dddZddZddZefeId׃rddddׄZecpdסefeIdكrddلZecpd١efeIdۃrddۄZecpdۡddZddZeFrddZddZddZ[[e jvddkr[[edkredS)a3psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. Supported platforms: - Linux - Windows - macOS - FreeBSD - OpenBSD - NetBSD - Sun Solaris - AIX Works with Python versions from 2.6 to 3.4+. )divisionN)_common) AccessDenied)Error)memoize_when_activated) NoSuchProcess)TimeoutExpired) wrap_numbers) ZombieProcess)long)PermissionError)ProcessLookupError)PY3) CONN_CLOSE)CONN_CLOSE_WAIT) CONN_CLOSING)CONN_ESTABLISHED)CONN_FIN_WAIT1)CONN_FIN_WAIT2) CONN_LAST_ACK) CONN_LISTEN) CONN_NONE) CONN_SYN_RECV) CONN_SYN_SENT)CONN_TIME_WAIT)NIC_DUPLEX_FULL)NIC_DUPLEX_HALF)NIC_DUPLEX_UNKNOWN)POWER_TIME_UNKNOWN)POWER_TIME_UNLIMITED) STATUS_DEAD)STATUS_DISK_SLEEP) STATUS_IDLE) STATUS_LOCKED) STATUS_PARKED)STATUS_RUNNING)STATUS_SLEEPING)STATUS_STOPPED)STATUS_TRACING_STOP)STATUS_WAITING) STATUS_WAKING) STATUS_ZOMBIE)AIX)BSD)FREEBSD)LINUX)MACOS)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWSz/proc)_pslinux)IOPRIO_CLASS_BE)IOPRIO_CLASS_IDLE)IOPRIO_CLASS_NONE)IOPRIO_CLASS_RT) _pswindows)ABOVE_NORMAL_PRIORITY_CLASS)BELOW_NORMAL_PRIORITY_CLASS)HIGH_PRIORITY_CLASS)IDLE_PRIORITY_CLASS)NORMAL_PRIORITY_CLASS)REALTIME_PRIORITY_CLASS)CONN_DELETE_TCB)IOPRIO_VERYLOW) IOPRIO_LOW) IOPRIO_NORMAL) IOPRIO_HIGH)_psosx)_psbsd)_pssunos) CONN_BOUND) CONN_IDLE)_psaixzplatform %s is not supportedrrr rr version_info __version__r&r#r'r"r(r)r,r!r+r$r*r%rrrrrrrrrrrrAF_LINKrrrrr r.r/r0r2r3r1r4r5r6r7r-ProcessPopen 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.8.0cCsg|] }t|qS)int).0numrjrjB/opt/alt/python38/lib64/python3.8/site-packages/psutil/__init__.py sro. monotonicversionzOversion conflict: %r C extension module was built for another version of psutil__file__z (%s instead of %s)cCsg|]}|qSrjrjrlxrjrjrnrosz (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_mapc CsDi}tD]4}zt|||<Wq ttfk r<Yq Xq |S)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )rU _psplatformrRppidrr )retpidrjrjrn _ppid_maps r|cstfdd}|S)zpDecorator which raises NoSuchProcess in case a process is no longer running or its PID has been reused. cs&|st|j|j|f||SN) is_runningrr{_nameselfargskwargsfunrjrnwrapper sz'_assert_pid_not_reused..wrapper) functoolswraps)rrrjrrn_assert_pid_not_reusedsrcCs8t}t||}|dkr"d}nd}tj||S)z(Format seconds in a human readable form.iQz%H:%M:%Sz%Y-%m-%d %H:%M:%S)timerkdatetime fromtimestampstrftime)ZsecsZnowZsecs_agoZfmtrjrjrn _pprint_secss  rc@seZdZdZdyddZdzddZdd ZeZd d Zd d Z ddZ e ddZ e jddZd{ddZddZddZddZeddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd|d,d-Zered.d/Zd0d1Z d2d3Z!d4d5Z"e#e$j%d6rd7d8Z&e#e$j%d9r&d}d:d;Z'e#e$j%d<r>d~d=d>Z(e#e$j%d?rVdd@dAZ)e#e$j%dBrldCdDZ*e#e$j%dErdFdGZ+e,rdHdIZ-dJdKZ.dLdMZ/e#e$j%dNrdOdPZ0e1ddQdRZ2ddSdTZ3edUdVZ4edWdXZ5e6j7dYdZd[d\Z8d]d^Z9dd`daZ:e#e$j%dbr$ddddeZ;dfdgZe1dmdnZ?e1dodpZ@e1dqdrZAe1dsdtZBe1dudvZCddwdxZDdS)rRa'Represents an OS process with the given PID. If PID is omitted current process PID (os.getpid()) is used. Raise NoSuchProcess if PID does not exist. Note that most of the methods of this class do not make sure the PID of the process being queried has been reused over time. That means you might end up retrieving an information referring to another process in case the original one this instance refers to is gone in the meantime. The only exceptions for which process identity is pre-emptively checked and guaranteed are: - parent() - children() - nice() (set) - ionice() (set) - rlimit() (set) - cpu_affinity (set) - suspend() - resume() - send_signal() - terminate() - kill() To prevent this problem for all other methods you can: - use is_running() before querying the process - if you're continuously iterating over a set of Process instances use process_iter() which pre-emptively checks process identity for every yielded instance NcCs||dSr})_init)rr{rjrjrn__init__EszProcess.__init__FcCs|dkrt}n2ts0t|ttfs0td||dkrDtd|||_d|_ d|_ d|_ d|_ d|_ t|_d|_t||_d|_d|_t|_z |WnXtk rYnFtk 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 isinstancerkr TypeError ValueError_pidr_exe _create_time_gone_hash threadingRLock_lock_ppidrxrR_proc_last_sys_cpu_times_last_proc_cpu_times _SENTINEL _exitcode create_timerr rr{_ident)rr{ _ignore_nspmsgrjrjrnrHs@      z Process._initc Csz t}Wntk r$i}YnX|j|d<|jr@|j|d<|z||d<||d<WnHtk rd|d<Yn.t k rd|d<Ynt k rYnX|j t dfkr|j |d<|j rt|j |d<d|jj|jjd d d |DfW5QRSQRXdS) Nr{namestatusZzombieZ terminatedZexitcodeZstartedz %s.%s(%s), cSsg|]\}}d||fqS)z%s=%rrj)rlkvrjrjrnrosz#Process.__str__..) collections OrderedDictAttributeErrorr{roneshotrrr rrrrrr __class__ __module____name__joinitems)rinforjrjrn__str__xs4         zProcess.__str__cCst|tstS|j|jkSr})rrRNotImplementedrrotherrjrjrn__eq__s zProcess.__eq__cCs ||k Sr}rjrrjrjrn__ne__szProcess.__ne__cCs|jdkrt|j|_|jSr})rhashrrrjrjrn__hash__s  zProcess.__hash__cCs|jS)zThe process PID.)rrrjrjrnr{sz Process.pidc cs|jt|drdVnzH|j ||j ||j |trP|j ||j dVW5|j||j||j|tr|j||j XW5QRXdS)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) rhasattrrZZcache_deactivate memory_inforyr5uidsrZ oneshot_exitZcache_activateZ oneshot_enterrrjrjrnrs"           zProcess.oneshotc Cst}|dk rnt|ttttfs.tdt|t|}||}|rntdt |dkrVdndd t t |ft }|pz|}|v|D]j}z$|dkr|j}nt||} | }Wn8ttfk r|}Yntk r|rYqYnX|||<qW5QRX|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 %srsrrrr{)_as_dict_attrnamesrlisttupleset frozensetrtyperlenrmapreprdictrr{getattrrr NotImplementedError) rattrsad_valueZ valid_names invalid_namesZretdictlsrrzZmethrjrjrnas_dicts8     zProcess.as_dictcCsttdk r tntd}|j|kr$dS|}|dk rp|}zt|}||krX|WSWntk rnYnXdS)zReturn the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None. Nr) _LOWEST_PIDrUr{ryrrRr)rZ lowest_pidryctimeparentrjrjrnrs   zProcess.parentcCs,g}|}|dk r(|||}q |S)zReturn the parents of this process as a list of Process instances. If no parents are known return an empty list. N)rappend)rparentsprocrjrjrnr-s   zProcess.parentscCsP|jr dSz|t|jkWStk r0YdStk rJd|_YdSXdS)zReturn whether this process is running. It also checks if PID has been reused by another process in which case return False. FTN)rrRr{r rrrjrjrnr~8szProcess.is_runningcCs*tr|jS|jp|j|_|jSdS)z`The process parent PID. On Windows the return value is cached after first call. N)r5rryrrrjrjrnryPs  z Process.ppidcCstr|jdk r|jS|j}trrt|dkrrz |}Wntk rNYn$X|rrtj |d}| |rr|}||_||j_|S)z>The process name. The return value is cached after first call.Nr) r7rrrr5rcmdlinerrpathbasename startswith)rrrZ extended_namerjrjrnrbs   z Process.namec sfdd}jdkrzj}Wn0tk rT}z||dWYSd}~XYn0X|s~z||d}Wntk r|YnX|_jS)zThe process executable as an absolute path. May also be an empty string. The return value is cached after first call. csd}|rRttdrRttdrR|d}tj|rRtj|rRt|tjrR|St|t r`||S)NaccessX_OKr) rrrrisabsisfilerrrr)fallbackrexerrjrnguess_its    zProcess.exe..guess_itN)r)rrrr)rrrerrrjrrnr|s   z Process.execCs |jS)z3The command line this process has been called with.)rrrrjrjrnrszProcess.cmdlinecCs*z |jWStk r$tYSXdS)z2The process current status as a STATUS_* constant.N)rrr r,rrjrjrnrs zProcess.statuscCsZtrLtdkrtd|j}zt|jWStk rHt|YSXn |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) r5pwd ImportErrorrrealgetpwuidZpw_nameKeyErrorstrrusername)rZreal_uidrjrjrnrs zProcess.usernamecCs|jdkr|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. N)rrrrrjrjrnrs  zProcess.create_timecCs |jS)z6Process current working directory as an absolute path.)rcwdrrjrjrnrsz Process.cwdcCs8|dkr|jS|s(t|j|j|j|dS)z'Get or set process niceness (priority).N)rZnice_getr~rr{rZnice_set)rvaluerjrjrnnices  z Process.nicecCs |jS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rrrrjrjrnrsz Process.uidscCs |jS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgidsrrjrjrnrsz Process.gidscCs |jS)zVThe terminal associated with this process, if any, else None. )rterminalrrjrjrnrszProcess.terminalcCs |jS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fdsrrjrjrnrszProcess.num_fds io_counterscCs |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. )rrrrjrjrnrszProcess.io_counters ionice_getcCs4|dkr"|dk rtd|jS|j||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)rrrZ ionice_set)rZioclassrrjrjrnionices  zProcess.ionicerhcCs|j||S)a-Get or set process resource limits as a (soft, hard) tuple. *resource* is one of the RLIMIT_* constants. *limits* is supposed to be a (soft, hard) tuple. See "man prlimit" for further info. Available on Linux and FreeBSD only. )rrh)rresourceZlimitsrjrjrnrhs zProcess.rlimitcpu_affinity_getcCsd|dkrtt|jS|sLt|jdr6|j}ntttt dd}|j t t|dS)a-Get or set process CPU affinity. If specified, *cpus* must be a list of CPUs for which you want to set the affinity (e.g. [0, 1]). If an empty list is passed, all egible CPUs are assumed (and set). (Windows, Linux and BSD only). N_get_eligible_cpusTpercpu) sortedrrrrrrrangerrZZcpu_affinity_setr)rZcpusrjrjrn cpu_affinity%s  zProcess.cpu_affinitycpu_numcCs |jS)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. )rrrrjrjrnr:szProcess.cpu_numenvironcCs |jS)zThe environment variables of the process as a dict. Note: this might not reflect changes made after the process started. )rrrrjrjrnrGszProcess.environcCs |jS)z\Return the number of handles opened by this process (Windows only). )r num_handlesrrjrjrnrNszProcess.num_handlescCs |jS)zkReturn the number of voluntary and involuntary context switches performed by this process. )rnum_ctx_switchesrrjrjrnrTszProcess.num_ctx_switchescCs |jS)z2Return the number of threads used by this process.)r num_threadsrrjrjrnrZszProcess.num_threadsthreadscCs |jS)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. )rrrrjrjrnr`szProcess.threadsc Cs,t}g}|sl|D]R\}}||jkrz&t|}||krL||Wqttfk rfYqXqnt t }|D]\}}|||q~t }|jg} | r(| }||krq| |||D]V} z6t| }||k} | r||| | Wqttfk r"YqXqq|S)u(Return the children of this process as a list of Process instances, pre-emptively checking whether PID has been reused. If *recursive* is True return all the parent descendants. Example (A == this process): A ─┐ │ ├─ B (child) ─┐ │ └─ X (grandchild) ─┐ │ └─ Y (great grandchild) ├─ C (child) └─ D (child) >>> import psutil >>> p = psutil.Process() >>> p.children() B, C, D >>> p.children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be listed as the reference to process A is lost. )r|rr{rRrrrr r defaultdictrrpopadd) r recursiverwrzr{ryZchildZreverse_ppid_mapseenstackZ child_pidZintimerjrjrnchildrenhs>       zProcess.childrenc s|dk o|dk}|dk r,|dkr,td|tp4dfdd}|rr|}|j}t||}|j}n<|j}|j}|}|j}|dks|dkr||_||_dS|j|j|j |j }||} ||_||_z|| d} Wnt k rYdSX| } 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 >>> Nr!interval is not positive (got %r)rcs tSr})_timerrjnum_cpusrjrntimersz"Process.cpu_percent..timerd) rr]rrZrsleeprrusersystemZeroDivisionErrorround) rintervalblockingrZst1Zpt1Zst2Zpt2Z delta_procZ delta_timeZoverall_cpus_percentZsingle_cpu_percentrjrrnr[s:#       zProcess.cpu_percentcCs |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. )rrZrrjrjrnrZ s zProcess.cpu_timescCs |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. )rrrrjrjrnrs zProcess.memory_infor)Z replacementcCs|Sr})rrrjrjrnmemory_info_ex szProcess.memory_info_excCs |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_inforrjrjrnr$szProcess.memory_full_inforsscCsttjj}||kr(td|t|f|tjjkr:|jn|j}|}t ||}t pZt j }|dksptd||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_PHYMEMrXtotalfloat)rZmemtypeZ valid_typesrZmetricsrZ total_phymemrjrjrnmemory_percent4s&   zProcess.memory_percent memory_mapsTc s|j}|ri|D]R}|d}|dd}ztdd|||<Wqtk rf||<YqXqtjfddDStjfdd|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||Sr}rj)rvyrjrjrndz%Process.memory_maps..csg|]}|f|qSrjrj)rlrdntrjrnrohsz'Process.memory_maps..csg|] }|qSrjrjru)r-rjrnroks)rr%rrrxZ pmmap_groupedZ pmmap_ext)rZgroupeditZtuplrnumsrjr+rnr%Rs  zProcess.memory_mapscCs |jS)zReturn files opened by process as a list of (path, fd) namedtuples including the absolute file name and file descriptor number. )r open_filesrrjrjrnr0mszProcess.open_filesinetcCs |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)rkindrjrjrnr2tszProcess.connectionscCs|jdkrtdzt|j|Wnjtk rntrVt|jrVt|j|j|j nd|_ t |j|jYn"t k rt |j|jYnXdS)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{rrkillrr3rTr rrrrr rrZsigrjrjrn _send_signals zProcess._send_signalcCs tr||n |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)r5r6r send_signalr5rjrjrnr7s zProcess.send_signalcCs tr|tjn |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)r5r6signalSIGSTOPrsuspendrrjrjrnr:szProcess.suspendcCs tr|tjn |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)r5r6r8SIGCONTrresumerrjrjrnr<szProcess.resumecCs tr|tjn |jdS)zTerminate the process with SIGTERM pre-emptively checking whether PID has been reused. On Windows this is an alias for kill(). N)r5r6r8SIGTERMrr4rrjrjrn terminateszProcess.terminatecCs tr|tjn |jdS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)r5r6r8SIGKILLrr4rrjrjrnr4sz Process.killcCs<|dk r|dkstd|jtk r(|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)rtimeoutrjrjrnr@s  z Process.wait)N)F)NN)N)NN)N)N)F)N)r)T)r1)N)Err __qualname____doc__rrr__repr__rrrpropertyr{ contextlibcontextmanagerrrrrr~rryrrrrrrrrr5rrrrrrxrRrrrhrrrr7rrrrrrr[rZrrZdeprecated_methodrrr$r%r0r2r6r7r:r<r>r4r@rjrjrjrnrR$s  0  B ,  '         E \           cCs"g|]}|ds|dkr|qS)_)r7r:r<r>r4r@r~rrrrrhrr)rrurjrjrnros  csJeZdZdZddZddZddZdd Zd d Zdfd d Z Z S)rSa Same as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class. For the following methods which are common to both classes, psutil implementation takes precedence: * send_signal() * terminate() * kill() This is done in order to avoid killing another process in case its PID has been reused, fixing BPO-6973. >>> import psutil >>> from subprocess import PIPE >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE) >>> p.name() 'python' >>> p.uids() user(real=1000, effective=1000, saved=1000) >>> p.username() 'giampaolo' >>> p.communicate() ('hi ', None) >>> p.terminate() >>> p.wait(timeout=2) 0 >>> cOs$tj|||_|j|jjdddS)NT)r) subprocessrS_Popen__subprocrr{rrjrjrnrszPopen.__init__cCsttttttjSr})rrdirrSrIrrjrjrn__dir__#sz Popen.__dir__cCst|jdr|j|S)N __enter__)rrJrMrrjrjrnrM&s  zPopen.__enter__cOs^t|jdr|jj||S|jr*|j|jr:|jz|jrL|jW5|XdS)N__exit__)rrJrNstdoutclosestderrr@stdinrrjrjrnrN+s   zPopen.__exit__c Csfzt||WStk r`zt|j|WYStk rZtd|jj|fYnXYnXdS)Nz!%s instance has no attribute '%s')object__getattribute__rrJrr)rrrjrjrnrT;s zPopen.__getattribute__Ncs0|jjdk r|jjStt||}||j_|Sr})rJ returncodesuperrSr@)rrArzrrjrnr@Es  z Popen.wait)N) rrrBrCrrLrMrNrTr@ __classcell__rjrjrWrnrSs cCstt}|da|S)z&Return a list of current running PIDs.r)rrxrUrrzrjrjrnrURs cCs0|dkr dS|dkr"tr"|tkSt|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)r5rUrxrTr{rjrjrnrTZs   c #sLfdd}dd}tt}tt}||}||}|D] }||q@t(ttttt |} W5QRX| D]\}} zJ| dkr||Vn2| rʈdk r| j d| _ | Vn ||VWqt k r||Yqtk rD| dkr>|tkr>zt|VWntk r:YnXnYqXqdS)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). c s>t|}dk r |jd|_t|t|j<W5QRX|S)Nrr)rRrrr_pmapr{)r{rrrrjrnr s zprocess_iter..addc Ss tt|dW5QRXdSr})rr\r rZrjrjrnremoveszprocess_iter..removeNr[)rrUr\keysrrrrrfromkeysr~rrrrr) rrr r^abZnew_pidsZ gone_pidsr{rrrjr]rnrVpsB       c s fdd}|dk r.|dks.d|}t|tt|}dk rXtsXtdt|dk rjt|}|r|dk r|dkrq|D]J}dt|}|dk rt|t|}|dkrq|||q|||q|}qj|r|D]}||dq|}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() csZz|j|d}Wntk r$Yn2X|dk s6|sV||_|dk rV|dS)N)rA)r@r r~rUr )rrArUcallbackZgonerjrn check_gones zwait_procs..check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg?)rrcallablerrrminr) ZprocsrArdrerZaliveZdeadlinerZ max_timeoutrjrcrnrWs6$        TcCs.|rt}nt}|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_physical)Zlogicalrzrjrjrnr]s  FcCs|s tStSdS)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)rxrZZ per_cpu_timesrrjrjrnrZ0srcCs0t|}tr,|t|dd8}|t|dd8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). ZguestrZ guest_nice)sumr0r)timesZtotrjrjrn _cpu_tot_timeYs  rjcCs&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)rjZidler)riZbusyrjrjrn_cpu_busy_timels rkcCsDg}tjjD],}t||t||}td|}||q tj|S)Nr)rx scputimesr rmaxr)t1t2Z field_deltasZfield field_deltarjrjrn_cpu_times_deltas|s    rqcCs|dk o|dk}|dk r,|dkr,td|dd}|sp|rNt}t|nt}|dkr`t}ta||tSg}|rtdd}t|nt}|dkrtdd}tddat|tD]\}}||||q|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 >>> NrrrcSsPt||}t|}t|}z||d}Wntk r@YdSXt|dSdS)Nrrr)rqrjrkrr)rnro times_delta all_deltaZ busy_deltaZ busy_percrjrjrn calculates zcpu_percent..calculateTr)rrZrr_last_cpu_times_last_per_cpu_timesziprrrrrtrnrzZtot1rorjrjrnr[s0%       cCs|dk o|dk}|dk r,|dkr,td|dd}|sp|rNt}t|nt}|dkr`t}ta||tSg}|rtdd}t|nt}|dkrtdd}tddat|tD]\}}||||q|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(). NrrrcSsdg}t||}t|}dtd|}|D]0}||}t|d}ttd|d}||q(tj|S)NgY@rr)rqrjrmrrgrrxrl)rnror/rrrsZscalerpZ field_percrjrjrnrts   z$cpu_times_percent..calculateTr)rrZrr_last_cpu_times_2_last_per_cpu_times_2rwrrxrjrjrnr\s0       cCstS)zReturn CPU statistics.)rxr^rjrjrjrnr^4scpu_freqc Cst}|r|Stt|}|dkr(dS|dkr8|dSd\}}}d}|D]6}||j7}trl|jdkrld}qJ||j7}||j7}qJ||}|rd} } n||} ||} t || | SdS)a9Return CPU frequency as a nameduple including current, min and max frequency expressed in Mhz. If *percpu* is True and the system supports per-cpu frequency retrieval (Linux only) a list of frequencies is returned for each CPU. If not a list with one element is returned. rNr)rrrFT) rxr{r#rcurrentr0rgrmrZscpufreq) rrzrZcurrsZminsZmaxsZset_noneZcpur|Zmin_Zmax_rjrjrnr{;s.       getloadavgcCst}|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. )rxrXr"r!rYrjrjrnrXvs5cCstS)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. )rxrYrjrjrjrnrYs cCs t|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. )rxre)rrjrjrnrescCsXdd}t|}trPg}|D],}|j||jd||jdd}||q|S|SdS)a3Return mounted partitions as a list of (device, mountpoint, fstype, opts) namedtuple. 'opts' field is a raw string separated by commas indicating mount options which may vary depending on the platform. If *all* parameter is False return physical devices only and ignore all others. c Ss,zt||WSttfk r&YnXdSr})rpathconfOSErrorr)rrrjrjrnr~sz!disk_partitions..pathconf PC_NAME_MAX PC_PATH_MAX)ZmaxfileZmaxpathN)rxrdr5_replaceZ mountpointr)allr~rznewitemr-rjrjrnrds     cCstrt|dni}tjf|}|s.|r*iSdS|r.) r0rrxrc _wrap_numbersrrrrrwvalues)rnowraprrawdictr-Zdiskfieldsrjrjrnrcs    rzClears nowrap argument cachecCsnt}|s|riSdS|r&t|d}|rN|D]\}}tj|||<q2|Stjddt|DSdS)adReturn network I/O statistics as a namedtuple including the following fields: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD) If *pernic* is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. Npsutil.net_io_counterscSsg|] }t|qSrjrrurjrjrnroGsz#net_io_counters..)rxr_rrrZsnetiorwr)ZpernicrrZnicrrjrjrnr_#s  rr1cCs t|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. )rxr`)r3rjrjrnr`Osc Cstjdk}|rddl}t}|jdddtt}|D]\}}}}}} |rz| |}WnBt k rt r|dkrtj }nt tdrtj |krtj }YnX|tj krtrd nd } || d kr|d | 7}q||t||||| q.)keyrQ:-z%s00)sysrOsocketrxrasortrrrZ AddressFamilyrr7rQrr5countrrZsnicaddrr) Z has_enumsrZrawlistrzrZfamZaddrmaskZ broadcastZptpZ separatorrjrjrnrals.       cCstS)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. )rxrbrjrjrjrnrbs sensors_temperaturesc sfdd}tt}t}|D]l\}}|r&|d\}}}} ||}||}|| } |rj| sj|} n | rv|sv| }||t |||| q.q&t |S)a<Return hardware temperatures. Each entry is a namedtuple representing a certain hardware sensor (it may be a CPU, an hard disk or something else, depending on the OS and its configuration). All temperatures are expressed in celsius unless *fahrenheit* is set to True. cs(|dk r$r t|dddS|SdS)N r )r#)n fahrenheitrjrnconvertsz%sensors_temperatures..convertr) rrrrxrrr rrZshwtempr) rrrzrrrZlabelr|ZhighZcriticalrjrrnrs"   sensors_fanscCstS)zReturn fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). )rxrrjrjrjrnrssensors_batterycCstS)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. )rxrrjrjrjrnrs cCstS)zAReturn the system boot time expressed in seconds since the epoch.)rxrgrjrjrjrnrgscCstS)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. )rxrfrjrjrjrnrf s cCstS)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )rxwin_service_iterrjrjrjrnr srcCs t|S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )rxwin_service_get)rrjrjrnr src CsXddlm}ddlm}tj}d}ddddd d d d d dg }t|dt|ddD]}|j d rtj |j d }||kr| d}q| d}nd}|j d rt dt t|j d }nd}|j dpd}|strz|d}Wntk r YnX|r2tr2d|kr2|dd}|dd}|j d dk r^||j d jnd} |j d dk r||j d jnd} |j ddk rt|j ddnd} |j d rt|j d nd} |j drd|j d} n |j d} |j d r|j d ddnd}||dd|j d| | | | |||| f }t|d|dqVdS)Nr) bytes2human)get_terminal_sizez)%-10s %5s %5s %7s %7s %5s %6s %6s %6s %sr{r$rrrZrrrrr) ZUSERZPIDz%MEMZVSZZRSSZNICEZSTATUSZSTARTZTIMEZCMDLINE)rz%H:%Mz%b%drrz%M:%Sr\r r )rr_compatrrdateZtodayprintrVrrrr localtimerhr5rrr7splitvmsrrrkr)rrZ today_dayZtemplrprZcputimerrrZmemprrrlinerjrjrntest% s~                 "  rr'__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r1)F)rCZ __future__rrrFrrrr8rIrrrrrrrrrrrrr r rr rr r rrrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7Z PROCFS_PATHr8rxr9r:r;r<r=Z_psutil_windowsr>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrplatform__all__extendZ__extra__all__rrRriglobalsZ_globalsrrKrisupperrrrQ __author__rPrrrOrr!rrSrrkreplaceZcextrrrrsrwr|rrrrrSrUrTr\ZLockrrVrWr]rZru Exceptionrvrjrkrqr[ryrzr\r^r{r}rXrYrerdrcpartial cache_clearr_r`rarbrrrrgrfrrrrmrvrrjrjrjrnsR                                                                          0          U T K ^      Z E  (   ;  / ' 0       =