3 JZKu@sZ dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z y ddlZWnek rdZYnXddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlm 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-ddlm.Z.dd lm/Z/dd!lm0Z0dd"lm1Z1dd#lm2Z2dd$lm3Z3dd%lm4Z4dd&lm5Z5dd'lm6Z6dd(lm7Z7dd)lm8Z8dd*lm9Z9dd+lm:Z:dd,lm;Z;dd-lmZ>dd0lm?Z?dd1l@mAZAdd2l@mBZBdd3l@mCZCdd4l@mDZDdd5l@mEZEe9rpd6ZFdd7lmGZHdd8lGmIZIdd9lGmJZJdd:lGmKZKdd;lGmLZLeHjMrVddlNmQZQdd?lNmRZRdd@lNmSZSddAlNmTZTddBlNmUZUddClNmVZVddDlNmWZWddElNmXZXddFlNmYZYddGlNmZZZddHlmNZNy eNj[Z[Wne\k rYnXy eNj]Z]Wne\k rYnXy eNj^Z^Wne\k r(YnXy eNj_Z_Wne\k rJYnXy eNj`Z`Wne\k rlYnXne?rddIlmaZHddJlbmcZcddKlbmdZdddLlbmeZeddMlbmfZfddNlbmgZgddOlbmhZhddPlamiZin~e<rddQlmjZHnje7rddRlmkZHnVe>r0ddSlmlZHddTllmmZmddUllmnZnd6ZFn&e6rHddVlmoZHd6ZFnepdWe jqdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidhdjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddgEZrerjseHjtdZudZvewddevjxdDZyeHjzZzej{Z{ej|Z|da}e~e de j Zeevjdde~eHjddkrde~eHjdZeeHjdreddjddeeHjjDevf7Zn edev7Zede~eHjdd7Zed7ZeeeeHdreHjZnddZddZddZGdddeZGdddeZeddeeDZddZddZiZdddZdddZdddZdddZy eaWn"ek rdae jYnXyeddaWn"ek rdae jYnXddZdd„ZdddZtatadddZddZeeHdƃr dddƄZerjdƃddZddZddZdddZdddZejejd̓e_dej_dddZejejdЃe_dej_dddZddZddZeeHdՃrdddՄZerjdՃeeHd׃rddׄZerjd׃eeHdكrddلZerjdكddZddZe? r"ddބZddZddZ[[[[e jyddk rF[[edk rVedS)a0psutil 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 - OSX - FreeBSD - OpenBSD - NetBSD - Sun Solaris - AIX Works with Python versions from 2.6 to 3.X. )divisionN)_common)deprecated_method)memoize)memoize_when_activated) wrap_numbers)callable)long)PY3) STATUS_DEAD)STATUS_DISK_SLEEP) STATUS_IDLE) STATUS_LOCKED)STATUS_RUNNING)STATUS_SLEEPING)STATUS_STOPPED)STATUS_TRACING_STOP)STATUS_WAITING) STATUS_WAKING) STATUS_ZOMBIE) 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)AIX)BSD)FREEBSD)LINUX)NETBSD)OPENBSD)OSX)POSIX)SUNOS)WINDOWS) AccessDenied)Error) NoSuchProcess)TimeoutExpired) ZombieProcessz/proc)_pslinux)IOPRIO_CLASS_BE)IOPRIO_CLASS_IDLE)IOPRIO_CLASS_NONE)IOPRIO_CLASS_RT) RLIM_INFINITY) RLIMIT_AS) RLIMIT_CORE) RLIMIT_CPU) RLIMIT_DATA) RLIMIT_FSIZE) RLIMIT_LOCKS)RLIMIT_MEMLOCK) RLIMIT_NOFILE) RLIMIT_NPROC) RLIMIT_RSS) RLIMIT_STACK) _psutil_linux) _pswindows)ABOVE_NORMAL_PRIORITY_CLASS)BELOW_NORMAL_PRIORITY_CLASS)HIGH_PRIORITY_CLASS)IDLE_PRIORITY_CLASS)NORMAL_PRIORITY_CLASS)REALTIME_PRIORITY_CLASS)CONN_DELETE_TCB)_psosx)_psbsd)_pssunos) CONN_BOUND) CONN_IDLE)_psaixzplatform %s is not supportedr1r2r4r0r3 version_info __version__rrrr rrrr rrrrr!r rrr"rrrrrrAF_LINKr#r$r%POWER_TIME_UNKNOWNPOWER_TIME_UNLIMITEDr'r(r)r*r+r,r-r.r/r&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_timezGiampaolo Rodola'z5.4.3cCsg|] }t|qS)int).0numrprp /usr/lib64/python3.6/__init__.py sru.Z monotonicversionzOversion conflict: %r C extension module was built for another version of psutil__file__z (%s instead of %s)cCsg|]}|qSrprp)rrxrprprtrusz (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 CsPi}xFtD]<}ytj|}|j}Wnttfk r>Yq X|||<q W|S)z{Return a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). )r] _psplatformrZppidr2r0)retpidprocr}rprprt _ppid_maps    rcstjfdd}|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_runningr2r_name)selfargskwargs)funrprtwrappersz'_assert_pid_not_reused..wrapper) functoolswraps)rrrp)rrt_assert_pid_not_reusedsrcCs8tj}t||}|dkr"d}nd}tjj|j|S)z(Format seconds in a human readable form.<z%H:%M:%Sz%Y-%m-%d %H:%M:%SiiQ)timerqdatetime fromtimestampstrftime)ZsecsZnowZsecs_agoZfmtrprprt _pprint_secs#s  rc@seZdZdZdwddZdxddZdd ZeZd d Zd d Z ddZ e ddZ e jddZdyddZddZddZeddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zdzd*d+Zered,d-Zd.d/Zd0d1Z d2d3Z!e"e#j$d4rd5d6Z%e"e#j$d7rd{d8d9Z&e"e#j$d:r4d|d;d<Z'e"e#j$d=rLd}d>d?Z(e"e#j$d@rbdAdBZ)e"e#j$dCrxdDdEZ*e+rdFdGZ,dHdIZ-dJdKZ.e"e#j$dLrdMdNZ/e0d~dOdPZ1ddQdRZ2edSdTZ3edUdVZ4e5dWdXdYdZZ6d[d\Z7dd^d_Z8e"e#j$d`rddbdcZ9dddeZ:ddgdhZ;er8didjZe0dodpZ?e0dqdrZ@e0dsdtZAddudvZBdS)rZa'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)rrrprprt__init__TszProcess.__init__Fc Cs|dkrtj}n6t r4t|ttf r4td||dkrHtd|||_d|_ d|_ d|_ d|_ d|_ d|_d|_tj||_d|_d|_y |jWnXtk 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 isinstancerqr TypeError ValueError_pidr_exe _create_time_gone_hash_oneshot_inctx_ppidr|rZ_proc_last_sys_cpu_times_last_proc_cpu_times create_timer0r4r2r_ident)rr _ignore_nspmsgrprprtrWs<     z Process._initcCsy tj}Wntk r$i}YnX|j|d<y$|j|d<|jrRt|j|d<WnHtk rpd|d<Yn.tk rd|d<Ynt k rYnXd|j j |j j dj d d |jDfS) NrnameZstartedZzombiestatusZ terminatedz %s.%s(%s)z, cSsg|]\}}d||fqS)z%s=%rrp)rrkvrprprtrusz#Process.__str__..) collections OrderedDictAttributeErrorrrrrr4r2r0 __class__ __module____name__joinitems)rinforprprt__str__s&      zProcess.__str__cCst|tstS|j|jkS)N)rrZNotImplementedr)rotherrprprt__eq__s zProcess.__eq__cCs ||k S)Nrp)rrrprprt__ne__szProcess.__ne__cCs|jdkrt|j|_|jS)N)rhashr)rrprprt__hash__s  zProcess.__hash__cCs|jS)zThe process PID.)r)rrprprtrsz Process.pidc cs|jrdVnd|_z@|jj|jj|jjtrB|jj|jjdVWd|jj |jj |jj tr|jj |jj d|_XdS)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 ... >>> NTF) rrbZcache_activate memory_infor}r-uidsrZ oneshot_enterZcache_deactivateZ oneshot_exit)rrprprtoneshots$            zProcess.oneshotc Cst}|dk rnt|ttttfs.tdt|t|}||}|rntdt |dkrVdnddj t t |ft }|pz|}|jxxp|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 %srsrwz, r)_as_dict_attrnamesrlisttupleset frozensetrtyperlenrmapreprdictrrgetattrr0r4NotImplementedError) rattrsad_valueZ valid_names invalid_namesZretdictZlsrr~methrprprtas_dicts6     zProcess.as_dictc CsN|j}|dk rJ|j}yt|}|j|kr2|SWntk rHYnXdS)zReturn the parent process as a Process object pre-emptively checking whether PID has been reused. If no parent is known return None. N)r}rrZr2)rr}ctimeparentrprprtrs zProcess.parentc CsJ|jr dSy|t|jkStk r,dStk rDd|_dSXdS)zReturn whether this process is running. It also checks if PID has been reused by another process in which case return False. FTN)rrZrr4r2)rrprprtr-szProcess.is_runningcCs*tr|jjS|jp|jj|_|jSdS)z`The process parent PID. On Windows the return value is cached after first call. N)r-rr}r)rrprprtr}Es  z Process.ppidc Cstr|jdk r|jS|jj}trrt|dkrry |j}Wntk rNYn$X|rrtj j |d}|j |rr|}||_||j_|S)z>The process name. The return value is cached after first call.Nr) r/rrrr-rcmdliner0rpathbasename startswith)rrrZ extended_namerprprtrWs   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) rhasattrrrisabsisfilerrrr0)fallbackrexe)rrprtguess_itvs   zProcess.exe..guess_itN)r)rrrr0)rrrerrrp)rrtrqs  z Process.execCs |jjS)z3The command line this process has been called with.)rr)rrprprtrszProcess.cmdlinec Cs$y |jjStk rtSXdS)z2The process current status as a STATUS_* constant.N)rrr4r)rrprprtrs zProcess.statusc CsTtrFtdkrtd|jj}y tj|jStk rBt|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) r-pwd ImportErrorrrealgetpwuidZpw_nameKeyErrorstrrusername)rZreal_uidrprprtrs   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)rrprprtrs  zProcess.create_timecCs |jjS)z6Process current working directory as an absolute path.)rcwd)rrprprtrsz Process.cwdcCs8|dkr|jjS|js(t|j|j|jj|dS)z'Get or set process niceness (priority).N)rZnice_getrr2rrZnice_set)rvaluerprprtnices  z Process.nicecCs |jjS)zVReturn process UIDs as a (real, effective, saved) namedtuple. )rr)rrprprtrsz Process.uidscCs |jjS)zVReturn process GIDs as a (real, effective, saved) namedtuple. )rgids)rrprprtrsz Process.gidscCs |jjS)zVThe terminal associated with this process, if any, else None. )rterminal)rrprprtrszProcess.terminalcCs |jjS)zcReturn the number of file descriptors opened by this process (POSIX only). )rnum_fds)rrprprtrszProcess.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)rrprprtrszProcess.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' argument must be specified)rrrZ ionice_set)rZioclassrrprprtionices  zProcess.ionicerlimitcCs&|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)rZresourceZlimitsrprprtr s  zProcess.rlimitcpu_affinity_getcCsd|dkrtt|jjS|sLt|jdr6|jj}ntttt dd}|jj tt|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) rrrrrrrrangerrbZcpu_affinity_set)rZcpusrprprt cpu_affinitys   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)rrprprtr5szProcess.cpu_numenvironcCs |jjS)zThe environment variables of the process as a dict. Note: this might not reflect changes made after the process started. )rr)rrprprtrBszProcess.environcCs |jjS)z\Return the number of handles opened by this process (Windows only). )r num_handles)rrprprtrIszProcess.num_handlescCs |jjS)zkReturn the number of voluntary and involuntary context switches performed by this process. )rnum_ctx_switches)rrprprtrOszProcess.num_ctx_switchescCs |jjS)z2Return the number of threads used by this process.)r num_threads)rrprprtrUszProcess.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)rrprprtr[szProcess.threadsc Cs<t}g}|spx^|jD]R\}}||jkry&t|}|j|jkrN|j|Wqttfk rhYqXqWntj t }x"|jD]\}}||j|qWt }|jg} x| r6| j }||krq|j |xb||D]V} y6t| }|j|jk} | r|j|| j| Wqttfk r.YqXqWqW|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. )rrrrZrappendr2r4r defaultdictrrpopadd) r recursiver{r~rr}ZchildZreverse_ppid_mapseenstackZ child_pidZintimerprprtchildrencs>     zProcess.childrenc s|dk o|dk}|dk r,|dkr,td|tp4dfdd}|rr|}|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)_timerrp)num_cpusrprttimersz"Process.cpu_percent..timerd) rrerrbrsleeprrusersystemZeroDivisionErrorround) rintervalblockingrZst1Zpt1Zst2Zpt2Z delta_procZ delta_timeZoverall_cpus_percentZsingle_cpu_percentrp)rrtrcs:#       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 OSX and Windows children_user and children_system are always set to 0. )rrb)rrprprtrbs 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 plaforms are `rss` and `vms`. All numbers are expressed in bytes. )rr)rrprprtrs zProcess.memory_infor)Z replacementcCs|jS)N)r)rrprprtmemory_info_exszProcess.memory_info_excCs |jjS)a[This method returns the same information as memory_info(), plus, on some platform (Linux, OSX, 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)rrprprtrszProcess.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 )rr|Zpfullmem_fieldsrrZpmemrrr _TOTAL_PHYMEMr`totalfloat)rZmemtypeZ valid_typesrZmetricsrZ total_phymemrprprtmemory_percent/s   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)Nrp)rzyrprprt`sz%Process.memory_maps..csg|]}|f|qSrprp)rrr)dntrprtrudsz'Process.memory_maps..csg|] }|qSrprp)rrrz)rrprtrugs)rrrrr|Z pmmap_groupedZ pmmap_ext)rZgroupeditZtuplrnumsrp)rrrtrNs   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)rrprprtr"iszProcess.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)rkindrprprtr$pszProcess.connectionscCs|jdkrtdytj|j|Wntk r}zj|jtjkrxtrdt|jrdt |j|j |j nd|_ t |j|j |jtjtjfkrt|j|j WYdd}~XnXdS)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)rrrkillOSErrorerrnoZESRCHr+r\r4rrrr2ZEPERMZEACCESr0)rsigrrprprt _send_signals  zProcess._send_signalcCs`tr|j|nL|tjkr&|jjn6|ttdtttdtfkrT|jj|nt ddS)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(). Z CTRL_C_EVENTZCTRL_BREAK_EVENTzPonly SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals are supported on WindowsN) r-r*signalSIGTERMrr&robject send_signalr)rr)rprprtr.s   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)r-r*r+SIGSTOPrsuspend)rrprprtr0szProcess.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)r-r*r+SIGCONTrresume)rrprprtr2szProcess.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)r-r*r+r,rr&)rrprprt terminateszProcess.terminatecCs tr|jtjn |jjdS)zjKill the current process with SIGKILL pre-emptively checking whether PID has been reused. N)r-r*r+SIGKILLrr&)rrprprtr&sz 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)rrwait)rtimeoutrprprtr5s z Process.wait)N)F)NN)N)NN)N)N)F)N)r)T)r#)N)Crr __qualname____doc__rrr__repr__rrrpropertyr contextlibcontextmanagerrrrrrr}rrrrrrrrr-rrrrrr|rZrrrrrrr/rrrrrrrcrbrrrrrrr"r$r*r.r0r2r3r&r5rprprprtrZ3s  / > , '         E \      csJeZdZdZddZddZddZdd Zd d Zdfd d Z Z S)r[azA more convenient interface to stdlib subprocess.Popen class. 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 whether 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__subprocrr)rrrrprprtrszPopen.__init__cCsttttttjS)N)sortedrdirr[r=)rrprprt__dir__"sz Popen.__dir__cCst|jdr|jj|S)N __enter__)rr>rB)rrprprtrB%s  zPopen.__enter__c Os^t|jdr|jj||S|jr*|jj|jr:|jjz|jrL|jjWd|jXdS)N__exit__)rr>rCstdoutclosestderrstdinr5)rrrrprprtrC*s   zPopen.__exit__cCs^y tj||Stk rXytj|j|Stk rRtd|jj|fYnXYnXdS)Nz!%s instance has no attribute '%s')r-__getattribute__rr>rr)rrrprprtrH:s zPopen.__getattribute__Ncs0|jjdk r|jjStt|j|}||j_|S)N)r> returncodesuperr[r5)rr6r~)rrprtr5Ds  z Popen.wait)N) rrr7r8rrArBrCrHr5 __classcell__rprp)rrtr[s! cCs$g|]}|jd r|dkr|qS)_r.r0r2r3r&r5rrrrrrr) r.r0r2r3r&r5rrrrrrr)r)rrrzrprprtruNscCstjS)z&Return a list of current running PIDs.)r|r]rprprprtr]YscCs0|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)r-r]r|r\)rrprprtr\^s   c #s@fdd}dd}tt}ttj}||}||}x|D] }||qBWxtttjttj|jD]\}} yJ| dkr||Vn2| j rdk r| j d| _ | Vn ||VWqvt k r||Yqvt k r6| dkr0|tkr0yt|VWntk r,YnXnYqvXqvWdS)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|_|t|j<|S)N)rr)rZrr_pmapr)rr)rrrprtrs  zprocess_iter..addcSstj|ddS)N)rMr)rrprprtremoveszprocess_iter..removeN)rr)rr]rMkeysr?rrrfromkeysrrrr2r0r) rrrrNabZnew_pidsZ gone_pidsrrrp)rrrtr^ss8       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)a,Convenience function which waits for a list of processes to terminate. Return a (gone, alive) tuple indicating which processes are gone and which ones are still alive. The gone ones will have a new *returncode* attribute indicating process exit status (may be None). *callback* is a function which gets called every time a process terminates (a Process instance is passed as callback argument). Function will return as soon as all processes terminate or when *timeout* occurs. Differently from Process.wait() it will not raise TimeoutExpired if *timeout* occurs. Typical use case is: - send SIGTERM to a list of processes - give them some time to terminate - send SIGKILL to those ones which are still alive Example: >>> def on_terminate(proc): ... print("process {} terminated".format(proc)) ... >>> for p in procs: ... p.terminate() ... >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate) >>> for p in alive: ... p.kill() c s\y|j|d}Wntk r$Yn4X|dk s8|j rX||_j|dk rX|dS)N)r6)r5r3rrIr)rr6rI)callbackgonerprt check_gones zwait_procs..check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg?)rrr rrrminr) Zprocsr6rSrUraliveZdeadlinerZ max_timeoutrp)rSrTrtr_s6$        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)r|Zcpu_count_logicalZcpu_count_physical)Zlogicalr~rprprtres  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)r|rbZ per_cpu_times)rrprprtrb-s)rcCs0t|}tr,|t|dd8}|t|dd8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time (including idle time). ZguestrZ guest_nice)sumr)r)timesZtotrprprt _cpu_tot_timeXs  rZcCs&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)rZZidler)rYZbusyrprprt_cpu_busy_timeks r[cCs|dk o|dk}|dk r,|dkr,td|dd}|sp|rNt}tj|nt}|dkr`t}ta||tSg}|rtdd}tj|nt}|dkrtdd}tddax&t|tD]\}}|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 Sspt|}t|}t|}t|}||kr,dS||}||}y||d}Wntk r`dSXt|dSdS)Ngr r)rZr[r r) t1t2Zt1_allZt1_busyZt2_allZt2_busyZ busy_delta all_deltaZ busy_percrprprt calculateszcpu_percent..calculateT)r)rrbrr _last_cpu_times_last_per_cpu_timeszipr)rrrr_r\r~tot1r]rprprtrc{s0%       cCs|dk o|dk}|dk r,|dkr,td|dd}|sp|rNt}tj|nt}|dkr`t}ta||tSg}|rtdd}tj|nt}|dkrtdd}tddax&t|tD]\}}|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)c Ssg}t|t|}xz|jD]p}t||t||}yd||}Wntk r\d}YnXt|d}|dkrvd}n |dkrd}|j|qWtj|S)Nr grgY@)rZrrr rrr|Z scputimes)r\r]r!r^ZfieldZ field_deltaZ field_percrprprtr_s   z$cpu_times_percent..calculateT)r)rrbrr _last_cpu_times_2_last_per_cpu_times_2rbr)rrrr_r\r~rcr]rprprtrds0       cCstjS)zReturn CPU statistics.)r|rfrprprprtrf/scpu_freqc Cstj}|r|Stt|}|dkr(dS|dkr8|dSd\}}}x*|D]"}||j7}||j7}||j7}qHW||}||}||} tj||| 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)rgrgrg) r|rfrrcurrentrVmaxrZscpufreq) rr~rZcurrsZminsZmaxsZcpurhZmin_Zmax_rprprtrf6s"     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 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: 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. )r|r`rr)r~rprprtr`Zs5cCstjS)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. )r|rarprprprtras 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. )r|rm)rrprprtrmscCs 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. )r|rl)allrprprtrls cCs|tj}|s|riSdS|r&t|d}ttdtj}|r^x |jD]\}}||||<qBW|S|ddt|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 ms) - write_time: time spent writing to disk (in ms) Platform specific: - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms) - read_merged_count (Linux): number of merged reads - write_merged_count (Linux): number of merged writes If *perdisk* is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedtuple described above as the values. If *nowrap* is True it detects and adjust the numbers which overflow and wrap (restart from 0) and add "old value" to "new value" so that the returned numbers will always be increasing or remain the same, but never decrease. "disk_io_counters.cache_clear()" can be used to invalidate the cache. On recent Windows versions 'diskperf -y' command may need to be executed first otherwise this function won't find any disk. Nzpsutil.disk_io_counterssdiskiocSsg|] }t|qSrp)rX)rrrzrprprtrusz$disk_io_counters..) r|rk _wrap_numbersrrrkrrbvalues)ZperdisknowraprawdictrZdiskfieldsrprprtrks   zpsutil.disk_io_counterszClears nowrap argument cachecCsrtj}|s|riSdS|r&t|d}|rRx"|jD]\}}tj|||<q4W|Stjddt|jDSdS)abReturn 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. 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. Nzpsutil.net_io_counterscSsg|] }t|qSrp)rX)rrrzrprprtrusz#net_io_counters..)r|rgrlrrZsnetiorbrm)ZpernicrnroZnicrprprprtrgs  zpsutil.net_io_countersr#cCs 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 OSX this function requires root privileges. )r|rh)r%rprprtrh"sc Cstjdk}|rddl}tj}|jdddtjt}x|D]\}}}}}} |ry|j |}WnBt k rt r|dkrtj }nt td rtj |krtj }YnX|tj krtrd nd } x|j| d kr|d | 7}qW||jtj||||| q>Wt|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. rrNcSs|dS)Nrrp)rzrprprtrUsznet_if_addrs..)keyrrW:-z%s00)rrq)sysrUsocketr|risortrrrZ AddressFamilyrr/rWrr-countrrZsnicr) Z has_enumsrxZrawlistr~rZfamZaddrmaskZ broadcastZptpZ separatorrprprtri?s,         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. )r|rjrprprprtrjos 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 ru )r)n) fahrenheitrprtconvertsz%sensors_temperatures..convertr) rrrr|r|rrrrZshwtempr) rrr~rorrmZlabelrhZhighZcriticalrp)rrtr|s      sensors_fanscCstjS)zReturn fans speed. Each entry is a namedtuple representing a certain hardware sensor. All speed are expressed in RPM (rounds per minute). )r|rrprprprtrssensors_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. )r|rrprprprtrs cCstjS)zAReturn the system boot time expressed in seconds since the epoch.)r|rorprprprtroscCstjS)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. )r|rnrprprprtrns cCstjS)zjReturn a generator yielding a WindowsService instance for all Windows services installed. )r|win_service_iterrprprprtrsrcCs tj|S)zjGet a Windows service by *name*. Raise NoSuchProcess if no service with such name exists. )r|win_service_get)rrprprtrsrc Cstjj}d}ddddddg}tr6|jd|jd t|dxrt|ddD]`}|jdrtjj|jd}|j|kr|j d}q|j d}nd}t j dt j t |jd}y |j }Wntk rd}YnXtod|kr|jdd}|jdrt|jdjdpd}|jdrBt|jdjdpDd}|jdrdt|jddpfd} t||dd|jd| |||jjd dpd|||jdjpdf qRWdS)zNList info of all currently running processes emulating ps aux output. z'%-10s %5s %4s %7s %7s %-13s %5s %7s %srrrrbrrrrUSERPID%MEMVSZRSSTTYSTARTTIMECOMMANDrw)rrz%H:%Mz%b%dz%M:%S\ri?N ) rrrrrrrrr)rZdateZtodayr-rprintr^rrrrZ localtimerXrr1r/splitrqvmsrrgetstrip) Z today_dayZtemplrprZcputimer rrZmemprprprttestsP              rr__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r#)F)r8Z __future__rrr;rr(rrr+r=rwr tracebackrrrwrrrrrrlZ_compatr r r rr r rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/ _exceptionsr0r1r2r3r4Z PROCFS_PATHr5r|r6r7r8r9Z HAS_PRLIMITrFr:r;r<r=r>r?r@rArBrCrDrEZRLIMIT_MSGQUEUErZ RLIMIT_NICEZ RLIMIT_RTPRIOZ RLIMIT_RTTIMEZRLIMIT_SIGPENDINGrGZ_psutil_windowsrHrIrJrKrLrMrNrOrPrQrRrSrTrplatform__all__extendZ__extra__all__ __author__rVrrrUrWrYrXrrrrqreplaceZcextrrrrrxr{rrrr-rZr[rr@rr]r\rMr^r_rerbr` Exception print_excrarZr[rcrdrerdrfrfrr`rarmrlrkpartial cache_clearrgrhrirjr|rrrornrrrrsrzrrprprprts                                                                                        &    LU  F ]    a O   ; .  '  0       0