博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
监控系统信息模块psutil
阅读量:4349 次
发布时间:2019-06-07

本文共 78383 字,大约阅读时间需要 261 分钟。

About

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization(CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoringprofilinglimiting process resources and the management of running processes. It implements many functionalities offered by UNIX command line tools such as: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap. psutil currently supports the following platforms:

  • Linux
  • Windows
  • macOS
  • FreeBSD, OpenBSDNetBSD
  • Sun Solaris
  • AIX

…both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.6 (users of Python 2.4 and 2.5 may use  version).  is also known to work.

The psutil documentation you’re reading is distributed as a single HTML page.

Install

The easiest way to install psutil is via pip:

pip install psutil

On UNIX this requires a C compiler (e.g. gcc) installed. On Windows pip will automatically retrieve a pre-compiled wheel version from . Alternatively, see more detailed  instructions.

Processes

Functions

psutil.
pids
()

Return a list of current running PIDs. To iterate over all processes and avoid race conditions  should be preferred.

>>> import psutil>>> psutil.pids() [1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
psutil.
process_iter
(attrs=Nonead_value=None)

Return an iterator yielding a  class instance for all running processes on the local machine. Every instance is only created once and then cached into an internal table which is updated every time an element is yielded. Cached  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. This is preferred over  for iterating over processes. Sorting order in which processes are returned is based on their PID. attrs and ad_value have the same meaning as in . If attrs is specified  is called internally and the resulting dict is stored as a info attribute which is attached to the returned  instances. If attrs is an empty list it will retrieve all process info (slow). Example usage:

>>> import psutil>>> for proc in psutil.process_iter(): ... try: ... pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) ... except psutil.NoSuchProcess: ... pass ... else: ... print(pinfo) ... {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'} ...

More compact version using attrs parameter:

>>> import psutil>>> for proc in psutil.process_iter(attrs=['pid', 'name', 'username']): ... print(proc.info) ... {'name': 'systemd', 'pid': 1, 'username': 'root'} {'name': 'kthreadd', 'pid': 2, 'username': 'root'} {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'} ...

Example of a dict comprehensions to create a {pid: info, ...} data structure:

>>> import psutil>>> procs = { p.pid: p.info for p in psutil.process_iter(attrs=['name', 'username'])} >>> procs {1: {'name': 'systemd', 'username': 'root'}, 2: {'name': 'kthreadd', 'username': 'root'}, 3: {'name': 'ksoftirqd/0', 'username': 'root'}, ...}

Example showing how to filter processes by name:

>>> import psutil>>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']] [{'name': 'python3', 'pid': 21947}, {'name': 'python', 'pid': 23835}]

See also  section for more examples.

Changed in version 5.3.0: added “attrs” and “ad_value” parameters.

psutil.
pid_exists
(pid)

Check whether the given PID exists in the current process list. This is faster than doing pid in psutil.pids() and should be preferred.

psutil.
wait_procs
(procstimeout=Nonecallback=None)

Convenience function which waits for a list of  instances 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 (will be None for processes which are not our children). callback is a function which gets called when one of the processes being waited on is terminated and a  instance is passed as callback argument). This function will return as soon as all processes terminate or when timeout(seconds) occurs. Differently from  it will not raise  if timeout occurs. A typical use case may be:

  • send SIGTERM to a list of processes
  • give them some time to terminate
  • send SIGKILL to those ones which are still alive

Example which terminates and waits all the children of this process:

import psutildef on_terminate(proc): print("process {} terminated with exit code {}".format(proc, proc.returncode)) procs = psutil.Process().children() for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate) for p in alive: p.kill()

Exceptions

class
psutil.
Error

Base exception class. All other exceptions inherit from this one.

class
psutil.
NoSuchProcess
(pidname=Nonemsg=None)

Raised by  class methods when no process with the given pid is found in the current process list or when a process no longer exists. name is the name the process had before disappearing and gets set only if  was previously called.

class
psutil.
ZombieProcess
(pidname=Noneppid=Nonemsg=None)

This may be raised by  class methods when querying a zombie process on UNIX (Windows doesn’t have zombie processes). Depending on the method called the OS may be able to succeed in retrieving the process information or not. Note: this is a subclass of  so if you’re not interested in retrieving zombies (e.g. when using ) you can ignore this exception and just catch .

New in version 3.0.0.

class
psutil.
AccessDenied
(pid=Nonename=Nonemsg=None)

Raised by  class methods when permission to perform an action is denied. “name” is the name of the process (may be None).

class
psutil.
TimeoutExpired
(secondspid=Nonename=Nonemsg=None)

Raised by  if timeout expires and process is still alive.

Process class

class
psutil.
Process
(pid=None)

Represents an OS process with the given pid. If pid is omitted current process pid () is used. Raise  if pid does not exist. On Linux pid can also refer to a thread ID (the id field returned by  method). When accessing methods of this class always be prepared to catch ,  and  exceptions.  builtin can be used against instances of this class in order to identify a process univocally over time (the hash is determined by mixing process PID and creation time). As such it can also be used with .

Note

 

In order to efficiently fetch more than one information about the process at the same time, make sure to use either or  context manager.

Note

 

the way this class is bound to a process is uniquely via its PID. That means that if the process terminates and the OS reuses its PID you may end up interacting with another process. The only exceptions for which process identity is preemptively checked (via PID + creation time) is for the following methods:  (set),  (set),  (set),  (set), ,,  , ,  . To prevent this problem for all other methods you can use before querying the process or  in case you’re iterating over all processes. It must be noted though that unless you deal with very “old” (inactive)  instances this will hardly represent a problem.

oneshot
()

Utility context manager which considerably speeds up the retrieval of multiple process information at the same time. Internally different process info (e.g. , , , , …) may be fetched by using the same routine, but only one value is returned and the others are discarded. When using this context manager the internal routine is executed once (in the example below on ) the value of interest is returned and the others are cached. The subsequent calls sharing the same internal routine will return the cached value. 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. Example:

>>> import psutil>>> p = psutil.Process() >>> with p.oneshot(): ... p.name() # execute internal routine once collecting multiple info ... p.cpu_times() # return cached value ... p.cpu_percent() # return cached value ... p.create_time() # return cached value ... p.ppid() # return cached value ... p.status() # return cached value ... >>>

Here’s a list of methods which can take advantage of the speedup depending on what platform you’re on. In the table below horizontal emtpy rows indicate what process methods can be efficiently grouped together internally. The last column (speedup) shows an approximation of the speedup you can get if you call all the methods together (best case scenario).

Linux Windows macOS BSD SunOS AIX
   
 
 
 
     
 
 
 
       
         
         
speedup: +2.6x speedup: +1.8x / +6.5x speedup: +1.9x speedup: +2.0x speedup: +1.3x speedup: +1.3x

New in version 5.0.0.

pid

The process PID. This is the only (read-only) attribute of the class.

ppid
()

The process parent PID. On Windows the return value is cached after first call. Not on POSIX because  if process becomes a zombie. See also  method.

name
()

The process name. On Windows the return value is cached after first call. Not on POSIX because the process name . See also how to .

exe
()

The process executable as an absolute path. On some systems this may also be an empty string. The return value is cached after first call.

>>> import psutil>>> psutil.Process().exe() '/usr/bin/python2.7'
cmdline
()

The command line this process has been called with as a list of strings. The return value is not cached because the cmdline of a process may change.

>>> import psutil>>> psutil.Process().cmdline() ['python', 'manage.py', 'runserver']
environ
()

The environment variables of the process as a dict. Note: this might not reflect changes made after the process started.

>>> import psutil>>> psutil.Process().environ() {'LC_NUMERIC': 'it_IT.UTF-8', 'QT_QPA_PLATFORMTHEME': 'appmenu-qt5', 'IM_CONFIG_PHASE': '1', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/giampaolo', 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated', 'XDG_CURRENT_DESKTOP': 'Unity', 'UPSTART_EVENTS': 'started starting', 'GNOME_KEYRING_PID': '', 'XDG_VTNR': '7', 'QT_IM_MODULE': 'ibus', 'LOGNAME': 'giampaolo', 'USER': 'giampaolo', 'PATH': '/home/giampaolo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/giampaolo/svn/sysconf/bin', 'LC_PAPER': 'it_IT.UTF-8', 'GNOME_KEYRING_CONTROL': '', 'GTK_IM_MODULE': 'ibus', 'DISPLAY': ':0', 'LANG': 'en_US.UTF-8', 'LESS_TERMCAP_se': '\x1b[0m', 'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'XDG_SESSION_PATH': '/org/freedesktop/DisplayManager/Session0', 'XAUTHORITY': '/home/giampaolo/.Xauthority', 'LANGUAGE': 'en_US', 'COMPIZ_CONFIG_PROFILE': 'ubuntu', 'LC_MONETARY': 'it_IT.UTF-8', 'QT_LINUX_ACCESSIBILITY_ALWAYS_ON': '1', 'LESS_TERMCAP_me': '\x1b[0m', 'LESS_TERMCAP_md': '\x1b[01;38;5;74m', 'LESS_TERMCAP_mb': '\x1b[01;31m', 'HISTSIZE': '100000', 'UPSTART_INSTANCE': '', 'CLUTTER_IM_MODULE': 'xim', 'WINDOWID': '58786407', 'EDITOR': 'vim', 'SESSIONTYPE': 'gnome-session', 'XMODIFIERS': '@im=ibus', 'GPG_AGENT_INFO': '/home/giampaolo/.gnupg/S.gpg-agent:0:1', 'HOME': '/home/giampaolo', 'HISTFILESIZE': '100000', 'QT4_IM_MODULE': 'xim', 'GTK2_MODULES': 'overlay-scrollbar', 'XDG_SESSION_DESKTOP': 'ubuntu', 'SHLVL': '1', 'XDG_RUNTIME_DIR': '/run/user/1000', 'INSTANCE': 'Unity', 'LC_ADDRESS': 'it_IT.UTF-8', 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh', 'VTE_VERSION': '4205', 'GDMSESSION': 'ubuntu', 'MANDATORY_PATH': '/usr/share/gconf/ubuntu.mandatory.path', 'VISUAL': 'vim', 'DESKTOP_SESSION': 'ubuntu', 'QT_ACCESSIBILITY': '1', 'XDG_SEAT_PATH': '/org/freedesktop/DisplayManager/Seat0', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'LESSOPEN': '| /usr/bin/lesspipe %s', 'XDG_SESSION_ID': 'c2', 'DBUS_SESSION_BUS_ADDRESS': 'unix:abstract=/tmp/dbus-9GAJpvnt8r', '_': '/usr/bin/python', 'DEFAULTS_PATH': '/usr/share/gconf/ubuntu.default.path', 'LC_IDENTIFICATION': 'it_IT.UTF-8', 'LESS_TERMCAP_ue': '\x1b[0m', 'UPSTART_SESSION': 'unix:abstract=/com/ubuntu/upstart-session/1000/1294', 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', 'GTK_MODULES': 'gail:atk-bridge:unity-gtk-module', 'XDG_SESSION_TYPE': 'x11', 'PYTHONSTARTUP': '/home/giampaolo/.pythonstart', 'LC_NAME': 'it_IT.UTF-8', 'OLDPWD': '/home/giampaolo/svn/curio_giampaolo/tests', 'GDM_LANG': 'en_US', 'LC_TELEPHONE': 'it_IT.UTF-8', 'HISTCONTROL': 'ignoredups:erasedups', 'LC_MEASUREMENT': 'it_IT.UTF-8', 'PWD': '/home/giampaolo/svn/curio_giampaolo', 'JOB': 'gnome-session', 'LESS_TERMCAP_us': '\x1b[04;38;5;146m', 'UPSTART_JOB': 'unity-settings-daemon', 'LC_TIME': 'it_IT.UTF-8', 'LESS_TERMCAP_so': '\x1b[38;5;246m', 'PAGER': 'less', 'XDG_DATA_DIRS': '/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop', 'XDG_SEAT': 'seat0'}

Availability: Linux, macOS, Windows, SunOS

New in version 4.0.0.

Changed in version 5.3.0: added SunOS support

create_time
()

The process creation time as a floating point number expressed in seconds since the epoch, in . The return value is cached after first call.

>>> import psutil, datetime>>> p = psutil.Process() >>> p.create_time() 1307289803.47 >>> datetime.datetime.fromtimestamp(p.create_time()).strftime("%Y-%m-%d %H:%M:%S") '2011-03-05 18:03:52'
as_dict
(attrs=Nonead_value=None)

Utility method retrieving multiple process information as a dictionary. If attrs is specified it must be a list of strings reflecting available class’s attribute names (e.g. ['cpu_times', 'name']), else all public (read only) attributes are assumed. ad_value is the value which gets assigned to a dict key in case  or  exception is raised when retrieving that particular process information. Internally,  uses  context manager so there’s no need you use it also.

>>> import psutil>>> p = psutil.Process() >>> p.as_dict(attrs=['pid', 'name', 'username']) {'username': 'giampaolo', 'pid': 12366, 'name': 'python'}

Changed in version 3.0.0: ad_value is used also when incurring into  exception, not only 

Changed in version 4.5.0:  is considerably faster thanks to  context manager.

parent
()

Utility method which returns the parent process as a  object preemptively checking whether PID has been reused. If no parent PID is known return None. See also  method.

status
()

The current process status as a string. The returned string is one of the  constants.

cwd
()

The process current working directory as an absolute path.

username
()

The name of the user that owns the process. On UNIX this is calculated by using real process uid.

uids
()

The real, effective and saved user ids of this process as a named tuple. This is the same as  but can be used for any process PID.

Availability: UNIX

gids
()

The real, effective and saved group ids of this process as a named tuple. This is the same as  but can be used for any process PID.

Availability: UNIX

terminal
()

The terminal associated with this process, if any, else None. This is similar to “tty” command but can be used for any process PID.

Availability: UNIX

nice
(value=None)

Get or set process  (priority). On UNIX this is a number which usually goes from -20 to 20. The higher the nice value, the lower the priority of the process.

>>> import psutil>>> p = psutil.Process() >>> p.nice(10) # set >>> p.nice() # get 10 >>>

Starting from  this functionality is also available as  and  (UNIX only). On Windows this is implemented via  and  Windows APIs and value is one of the  constants reflecting the MSDN documentation. Example which increases process priority on Windows:

>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
ionice
(ioclass=Nonevalue=None)

Get or set  (priority). On Linux ioclass is one of the  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). The example below sets IDLE priority class for the current process, meaning it will only get I/O time when no other process needs the disk:

>>> import psutil>>> p = psutil.Process() >>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # set >>> p.ionice() # get pionice(ioclass=
, value=0) >>>

On Windows only ioclass is used and it can be set to 2 (normal), 1 (low) or 0 (very low). Also it returns an integer instead of a named tuple.

Availability: Linux and Windows > Vista

Changed in version 3.0.0: on Python >= 3.4 the returned ioclass constant is an  instead of a plain integer.

rlimit
(resourcelimits=None)

Get or set process resource limits (see ). resource is one of the  constants. limits is a (soft, hard) tuple. This is the same as  and  but can be used for any process PID, not only . For get, return value is a (soft, hard) tuple. Each value may be either and integer or . Example:

>>> import psutil>>> p = psutil.Process() >>> # process may open no more than 128 file descriptors >>> p.rlimit(psutil.RLIMIT_NOFILE, (128, 128)) >>> # process may create files no bigger than 1024 bytes >>> p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024)) >>> # get >>> p.rlimit(psutil.RLIMIT_FSIZE) (1024, 1024) >>>

Availability: Linux

io_counters
()

Return process I/O statistics as a named tuple. For Linux you can refer to .

  • read_count: the number of read operations performed (cumulative). This is supposed to count the number of read-related syscalls such as read() and pread() on UNIX.
  • write_count: the number of write operations performed (cumulative). This is supposed to count the number of write-related syscalls such as write() and pwrite() on UNIX.
  • read_bytes: the number of bytes read (cumulative). Always -1 on BSD.
  • write_bytes: the number of bytes written (cumulative). Always -1 on BSD.

Linux specific:

  • read_chars (Linux): the amount of bytes which this process passed to read() and pread() syscalls (cumulative). Differently from read_bytes it doesn’t care whether or not actual physical disk I/O occurred.
  • write_chars (Linux): the amount of bytes which this process passed to write() and pwrite() syscalls (cumulative). Differently from write_bytes it doesn’t care whether or not actual physical disk I/O occurred.

Windows specific:

  • other_count (Windows): the number of I/O operations performed other than read and write operations.
  • other_bytes (Windows): the number of bytes transferred during operations other than read and write operations.
>>> import psutil>>> p = psutil.Process() >>> p.io_counters() pio(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0, read_chars=769931, write_chars=203)

Availability: Linux, BSD, Windows, AIX

Changed in version 5.2.0: added read_chars and write_chars on Linux; added other_count and other_bytes on Windows.

num_ctx_switches
()

The number voluntary and involuntary context switches performed by this process (cumulative).

Changed in version 5.4.1: added AIX support

num_fds
()

The number of file descriptors currently opened by this process (non cumulative).

Availability: UNIX

num_handles
()

The number of handles currently used by this process (non cumulative).

Availability: Windows

num_threads
()

The number of threads currently used by this process (non cumulative).

threads
()

Return threads opened by process as a list of named tuples including thread id and thread CPU times (user/system). On OpenBSD this method requires root privileges.

cpu_times
()

Return a (user, system, children_user, children_system) named tuple representing the accumulated process time, in seconds (see). On Windows and macOS only user and system are filled, the others are set to 0. This is similar to  but can be used for any process PID.

Changed in version 4.1.0: return two extra fields: children_user and children_system.

cpu_percent
(interval=None)

Return a float representing the process CPU utilization as a percentage which can also be 100.0 in case of a process running multiple threads on different CPUs. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called a second time with at least 0.1 seconds between calls. Example:

>>> import psutil>>> p = psutil.Process() >>> # blocking >>> p.cpu_percent(interval=1) 2.0 >>> # non-blocking (percentage since last call) >>> p.cpu_percent(interval=None) 2.9

Note

 

the returned value can be > 100.0 in case of a process running multiple threads on different CPU cores.

Note

 

the returned value is explicitly not split evenly between all available CPUs (differently from ). 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%. This was done in order to be consistent with top UNIX utility and also to make it easier to identify processes hogging CPU resources independently from the number of CPUs. It must be noted that taskmgr.exe on Windows does not behave like this (it would report 50% usage instead). To emulate Windows taskmgr.exe behavior you can do:p.cpu_percent() psutil.cpu_count().

Warning

 

the first time this method is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

cpu_affinity
(cpus=None)

Get or set process current . CPU affinity consists in telling the OS to run a process on a limited set of CPUs only (on Linux cmdline, taskset command is typically used). If no argument is passed it returns the current CPU affinity as a list of integers. If passed it must be a list of integers specifying the new CPUs affinity. If an empty list is passed all eligible CPUs are assumed (and set). On some systems such as Linux this may not necessarily mean all available logical CPUs as in list(range(psutil.cpu_count()))).

>>> import psutil>>> psutil.cpu_count() 4 >>> p = psutil.Process() >>> # get >>> p.cpu_affinity() [0, 1, 2, 3] >>> # set; from now on, process will run on CPU #0 and #1 only >>> p.cpu_affinity([0, 1]) >>> p.cpu_affinity() [0, 1] >>> # reset affinity against all eligible CPUs >>> p.cpu_affinity([])

Availability: Linux, Windows, FreeBSD

Changed in version 2.2.0: added support for FreeBSD

Changed in version 5.1.0: an empty list can be passed to set affinity against all eligible CPUs.

cpu_num
()

Return what CPU this process is currently running on. The returned number should be <= . On FreeBSD certain kernel process may return -1. It may be used in conjunction with psutil.cpu_percent(percpu=True) to observe the system workload distributed across multiple CPUs as shown by  example script.

Availability: Linux, FreeBSD, SunOS

New in version 5.1.0.

memory_info
()

Return a named tuple 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.

Linux macOS BSD Solaris AIX Windows
rss rss rss rss rss rss (alias for wset)
vms vms vms vms vms vms (alias for pagefile)
shared pfaults text     num_page_faults
text pageins data     peak_wset
lib   stack     wset
data         peak_paged_pool
dirty         paged_pool
          peak_nonpaged_pool
          nonpaged_pool
          pagefile
          peak_pagefile
          private
  • rss: aka “Resident Set Size”, this is the non-swapped physical memory a process has used. On UNIX it matches “top“‘s RES column (see ). On Windows this is an alias for wset field and it matches “Mem Usage” column of taskmgr.exe.
  • vms: aka “Virtual Memory Size”, this is the total amount of virtual memory used by the process. On UNIX it matches “top“‘s VIRT column (see ). On Windows this is an alias for pagefile field and it matches “Mem Usage” “VM Size” column of taskmgr.exe.
  • shared(Linux) memory that could be potentially shared with other processes. This matches “top“‘s SHR column (see ).
  • text (Linux, BSD): aka TRS (text resident set) the amount of memory devoted to executable code. This matches “top“‘s CODE column (see ).
  • data (Linux, BSD): aka DRS (data resident set) the amount of physical memory devoted to other than executable code. It matches “top“‘s DATA column (see ).
  • lib (Linux): the memory used by shared libraries.
  • dirty (Linux): the number of dirty pages.
  • pfaults (macOS): number of page faults.
  • pageins (macOS): number of actual pageins.

For on explanation of Windows fields rely on  structure doc. Example on Linux:

>>> import psutil>>> p = psutil.Process() >>> p.memory_info() pmem(rss=15491072, vms=84025344, shared=5206016, text=2555904, lib=0, data=9891840, dirty=0)

Changed in version 4.0.0: multiple fields are returned, not only rss and vms.

memory_info_ex
()

Same as  (deprecated).

Warning

 

deprecated in version 4.0.0; use  instead.

memory_full_info
()

This method returns the same information as , plus, on some platform (Linux, macOS, Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better representation of “effective” process memory consumption (in case of USS) as explained in detail in this . It does so by passing through the whole process address. As such it usually requires higher user privileges than  and is considerably slower. On platforms where extra fields are not implemented this simply returns the same metrics as .

  • uss (Linux, macOS, Windows): aka “Unique Set Size”, this is the memory which is unique to a process and which would be freed if the process was terminated right now.
  • pss (Linux): aka “Proportional Set Size”, is the amount of memory shared with other processes, accounted in a way that the amount is divided evenly between the processes that share it. I.e. if a process has 10 MBs all to itself and 10 MBs shared with another process its PSS will be 15 MBs.
  • swap (Linux): amount of memory that has been swapped out to disk.

Note

 

uss is probably the most representative metric for determining how much memory is actually being used by a process. It represents the amount of memory that would be freed if the process was terminated right now.

Example on Linux:

>>> import psutil>>> p = psutil.Process() >>> p.memory_full_info() pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0) >>>

See also  for an example application.

New in version 4.0.0.

memory_percent
(memtype="rss")

Compare process memory to total physical system memory and calculate process memory utilization as a percentage. memtypeargument is a string that dictates what type of process memory you want to compare against. You can choose between the named tuple field names returned by  and  (defaults to "rss").

Changed in version 4.0.0: added memtype parameter.

memory_maps
(grouped=True)

Return process’s mapped memory regions as a list of named tuples whose fields are variable depending on the platform. This method is useful to obtain a detailed representation of process memory usage as explained  (the most important value is “private” memory). 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 each mapped region is shown as a single entity and the named tuple will also include the mapped region’s address space (addr) and permission set (perms). See  for an example application.

Linux macOS Windows Solaris FreeBSD
rss rss rss rss rss
size private   anonymous private
pss swapped   locked ref_count
shared_clean dirtied     shadow_count
shared_dirty ref_count      
private_clean shadow_depth      
private_dirty        
referenced        
anonymous        
swap        
>>> import psutil>>> p = psutil.Process() >>> p.memory_maps() [pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0), pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0), pmmap_grouped(path='/lib/x8664-linux-gnu/libcrypto.so.0.1', rss=34124, rss=32768, size=2134016, pss=15360, shared_clean=24576, shared_dirty=0, private_clean=0, private_dirty=8192, referenced=24576, anonymous=8192, swap=0), pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0), pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0), ...] >>> p.memory_maps(grouped=False) [pmmap_ext(addr='00400000-006ea000', perms='r-xp', path='/usr/bin/python2.7', rss=2293760, size=3055616, pss=1157120, shared_clean=2273280, shared_dirty=0, private_clean=20480, private_dirty=0, referenced=2293760, anonymous=0, swap=0), pmmap_ext(addr='008e9000-008eb000', perms='r--p', path='/usr/bin/python2.7', rss=8192, size=8192, pss=6144, shared_clean=4096, shared_dirty=0, private_clean=0, private_dirty=4096, referenced=8192, anonymous=4096, swap=0), pmmap_ext(addr='008eb000-00962000', perms='rw-p', path='/usr/bin/python2.7', rss=417792, size=487424, pss=317440, shared_clean=200704, shared_dirty=0, private_clean=16384, private_dirty=200704, referenced=417792, anonymous=200704, swap=0), pmmap_ext(addr='00962000-00985000', perms='rw-p', path='[anon]', rss=139264, size=143360, pss=139264, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=139264, referenced=139264, anonymous=139264, swap=0), pmmap_ext(addr='02829000-02ccf000', perms='rw-p', path='[heap]', rss=4743168, size=4874240, pss=4743168, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=4743168, referenced=4718592, anonymous=4743168, swap=0), ...]

Availability: All platforms except OpenBSD, NetBSD and AIX.

children
(recursive=False)

Return the children of this process as a list of  instances. If recursive is True return all the parent descendants. Pseudo code example assuming A == this process:

A ─┐   │   ├─ B (child) ─┐   │             └─ X (grandchild) ─┐   │                                └─ Y (great grandchild)   ├─ C (child)   └─ D (child)>>> 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 returned either as the reference to process A is lost. This concept is well summaried by this . See also how to  and .

open_files
()

Return regular files opened by process as a list of named tuples including the following fields:

  • path: the absolute file name.
  • fd: the file descriptor number; on Windows this is always -1.

Linux only:

  • position (Linux): the file (offset) position.
  • mode (Linux): a string indicating how the file was opened, similarly ’s mode argument. Possible values are 'r''w''a','r+' and 'a+'. There’s no distinction between files opened in bynary or text mode ("b" or "t").
  • flags (Linux): the flags which were passed to the underlying  C call when the file was opened (e.g. ,, etc).
>>> import psutil>>> f = open('file.ext', 'w') >>> p = psutil.Process() >>> p.open_files() [popenfile(path='/home/giampaolo/svn/psutil/file.ext', fd=3, position=0, mode='w', flags=32769)]

Warning

 

on Windows this method is not reliable due to some limitations of the underlying Windows API which may hang when retrieving certain file handles. In order to work around that psutil spawns a thread for each handle and kills it if it’s not responding after 100ms. That implies that this method on Windows is not guaranteed to enumerate all regular file handles (see ). Also, it will only list files living in the C:\ drive (see ).

Warning

 

on BSD this method can return files with a null path (“”) due to a kernel bug, hence it’s not reliable (see ).

Changed in version 3.1.0: no longer hangs on Windows.

Changed in version 4.1.0: new positionmode and flags fields on Linux.

connections
(kind="inet")

Return socket connections opened by process as a list of named tuples. To get system-wide connections use . Every named tuple provides 6 attributes:

  • fd: the socket file descriptor. This can be passed to  to obtain a usable socket object. On Windows, FreeBSD and SunOS this is always set to -1.
  • family: the address family, either ,  or .
  • type: the address type, either  or .
  • laddr: the local address as a (ip, port) named tuple or a path in case of AF_UNIX sockets. For UNIX sockets see notes below.
  • raddr: the remote address as a (ip, port) named tuple or an absolute path in case of UNIX sockets. When the remote endpoint is not connected you’ll get an empty tuple (AF_INET*) or "" (AF_UNIX). For UNIX sockets see notes below.
  • status: represents the status of a TCP connection. The return value is one of the  constants. For UDP and UNIX sockets this is always going to be .

The kind parameter is a string which 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

Example:

>>> import psutil>>> p = psutil.Process(1694) >>> p.name() 'firefox' >>> p.connections() [pconn(fd=115, family=
, type=
, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'), pconn(fd=117, family=
, type=
, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING'), pconn(fd=119, family=
, type=
, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED'), pconn(fd=123, family=
, type=
, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT')]

Note

 

(Solaris) UNIX sockets are not supported.

Note

 

(Linux, FreeBSD) “raddr” field for UNIX sockets is always set to “”. This is a limitation of the OS.

Note

 

(OpenBSD) “laddr” and “raddr” fields for UNIX sockets are always set to “”. This is a limitation of the OS.

Note

 

(AIX)  is always raised unless running as root (lsof does the same).

Changed in version 5.3.0: : “laddr” and “raddr” are named tuples.

is_running
()

Return whether the current process is running in the current process list. This is reliable also in case the process is gone and its PID reused by another process, therefore it must be preferred over doing psutil.pid_exists(p.pid).

Note

 

this will return True also if the process is a zombie (p.status() == psutil.STATUS_ZOMBIE).

send_signal
(signal)

Send a signal to process (see  constants) preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, sig). On Windows only SIGTERMCTRL_C_EVENT and CTRL_BREAK_EVENT signals are supported and SIGTERMis treated as an alias for . See also how to  and .

Changed in version 3.2.0: support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals on Windows was added.

suspend
()

Suspend process execution with SIGSTOP signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGSTOP). On Windows this is done by suspending all process threads execution.

resume
()

Resume process execution with SIGCONT signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGCONT). On Windows this is done by resuming all process threads execution.

terminate
()

Terminate the process with SIGTERM signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGTERM). On Windows this is an alias for . See also how to  and .

kill
()

Kill the current process by using SIGKILL signal preemptively checking whether PID has been reused. On UNIX this is the same as os.kill(pid, signal.SIGKILL). On Windows this is done by using . See also how to  and .

wait
(timeout=None)

Wait for process termination and if the process is a child of the current one also return the 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. timeout is expressed in seconds. If specified and the process is still alive raise  exception. timeout=0 can be used in non-blocking apps: it will either return immediately or raise . To wait for multiple processes use .

>>> import psutil>>> p = psutil.Process(9891) >>> p.terminate() >>> p.wait()

Popen class

class
psutil.
Popen
(*args**kwargs)

A more convenient interface to stdlib . It starts a sub process and you deal with it exactly as when using but in addition it also provides all the methods of  class. For method names common to both classes such as ,  and   implementation takes precedence. For a complete documentation refer to .

Note

 

Unlike  this class preemptively checks whether PID has been reused on ,  and so that you can’t accidentally terminate another process, fixing .

>>> import psutil>>> from subprocess import PIPE >>> >>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE) >>> p.name() 'python' >>> p.username() 'giampaolo' >>> p.communicate() ('hello\n', None) >>> p.wait(timeout=2) 0 >>>

 objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for. This is supported on all Python versions.

>>> import psutil, subprocess>>> with psutil.Popen(["ifconfig"], stdout=subprocess.PIPE) as proc: >>> log.write(proc.stdout.read())

Changed in version 4.4.0: added context manager support

Windows services

psutil.
win_service_iter
()

Return an iterator yielding a  class instance for all Windows services installed.

New in version 4.2.0.

Availability: Windows

psutil.
win_service_get
(name)

Get a Windows service by name, returning a  instance. Raise  if no service with such name exists.

New in version 4.2.0.

Availability: Windows

class
psutil.
WindowsService

Represents a Windows service with the given name. This class is returned by  and  functions and it is not supposed to be instantiated directly.

name
()

The service name. This string is how a service is referenced and can be passed to  to get a new instance.

display_name
()

The service display name. The value is cached when this class is instantiated.

binpath
()

The fully qualified path to the service binary/exe file as a string, including command line arguments.

username
()

The name of the user that owns this service.

start_type
()

A string which can either be “automatic”“manual” or “disabled”.

pid
()

The process PID, if any, else None. This can be passed to  class to control the service’s process.

status
()

Service status as a string, which may be either “running”“paused”“start_pending”“pause_pending”“continue_pending”“stop_pending”or “stopped”.

description
()

Service long description.

as_dict
()

Utility method retrieving all the information above as a dictionary.

New in version 4.2.0.

Availability: Windows

Example code:

>>> import psutil>>> list(psutil.win_service_iter()) [
,
,
,
, ...] >>> s = psutil.win_service_get('alg') >>> s.as_dict() {'binpath': 'C:\\Windows\\System32\\alg.exe', 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing', 'display_name': 'Application Layer Gateway Service', 'name': 'alg', 'pid': None, 'start_type': 'manual', 'status': 'stopped', 'username': 'NT AUTHORITY\\LocalService'}

Constants

psutil.
POSIX
psutil.
WINDOWS
psutil.
LINUX
psutil.
MACOS
psutil.
FREEBSD
psutil.
NETBSD
psutil.
OPENBSD
psutil.
BSD
psutil.
SUNOS
psutil.
AIX

bool constants which define what platform you’re on. E.g. if on Windows,  constant will be True, all others will be False.

New in version 4.0.0.

Changed in version 5.4.0: added AIX

psutil.
OSX

Alias for  (deprecated).

Warning

 

deprecated in version 5.4.7; use  instead.

psutil.
PROCFS_PATH

The path of the /proc filesystem on Linux, Solaris and AIX (defaults to "/proc"). You may want to re-set this constant right after importing psutil in case your /proc filesystem is mounted elsewhere or if you want to retrieve information about Linux containers such as ,  or  (see  for more info). It must be noted that this trick works only for APIs which rely on /proc filesystem (e.g.  APIs and most  class methods).

Availability: Linux, Solaris, AIX

New in version 3.2.3.

Changed in version 3.4.2: also available on Solaris.

Changed in version 5.4.0: also available on AIX.

psutil.
STATUS_RUNNING
psutil.
STATUS_SLEEPING
psutil.
STATUS_DISK_SLEEP
psutil.
STATUS_STOPPED
psutil.
STATUS_TRACING_STOP
psutil.
STATUS_ZOMBIE
psutil.
STATUS_DEAD
psutil.
STATUS_WAKE_KILL
psutil.
STATUS_WAKING
psutil.
STATUS_PARKED
(Linux)
psutil.
STATUS_IDLE
(LinuxmacOSFreeBSD)
psutil.
STATUS_LOCKED
(FreeBSD)
psutil.
STATUS_WAITING
(FreeBSD)
psutil.
STATUS_SUSPENDED
(NetBSD)

A set of strings representing the status of a process. Returned by .

New in version 3.4.1: STATUS_SUSPENDED (NetBSD)

New in version 5.4.7: STATUS_PARKED (Linux)

psutil.
CONN_ESTABLISHED
psutil.
CONN_SYN_SENT
psutil.
CONN_SYN_RECV
psutil.
CONN_FIN_WAIT1
psutil.
CONN_FIN_WAIT2
psutil.
CONN_TIME_WAIT
psutil.
CONN_CLOSE
psutil.
CONN_CLOSE_WAIT
psutil.
CONN_LAST_ACK
psutil.
CONN_LISTEN
psutil.
CONN_CLOSING
psutil.
CONN_NONE
psutil.
CONN_DELETE_TCB
(Windows)
psutil.
CONN_IDLE
(Solaris)
psutil.
CONN_BOUND
(Solaris)

A set of strings representing the status of a TCP connection. Returned by  (status field).

psutil.
ABOVE_NORMAL_PRIORITY_CLASS
psutil.
BELOW_NORMAL_PRIORITY_CLASS
psutil.
HIGH_PRIORITY_CLASS
psutil.
IDLE_PRIORITY_CLASS
psutil.
NORMAL_PRIORITY_CLASS
psutil.
REALTIME_PRIORITY_CLASS

A set of integers representing the priority of a process on Windows (see ). They can be used in conjunction with to get or set process priority.

Availability: Windows

Changed in version 3.0.0: on Python >= 3.4 these constants are  instead of a plain integer.

psutil.
IOPRIO_CLASS_NONE
psutil.
IOPRIO_CLASS_RT
psutil.
IOPRIO_CLASS_BE
psutil.
IOPRIO_CLASS_IDLE

A set of integers representing the I/O priority of a process on Linux. They can be used in conjunction with  to get or set process I/O priority. IOPRIO_CLASS_NONE and IOPRIO_CLASS_BE (best effort) is the default for any process that hasn’t set a specific I/O priority. IOPRIO_CLASS_RT (real time) means the process is given first access to the disk, regardless of what else is going on in the system. IOPRIO_CLASS_IDLE means the process will get I/O time when no-one else needs the disk. For further information refer to manuals of  command line utility or  system call.

Availability: Linux

Changed in version 3.0.0: on Python >= 3.4 these constants are  instead of a plain integer.

psutil.
RLIM_INFINITY
psutil.
RLIMIT_AS
psutil.
RLIMIT_CORE
psutil.
RLIMIT_CPU
psutil.
RLIMIT_DATA
psutil.
RLIMIT_FSIZE
psutil.
RLIMIT_LOCKS
psutil.
RLIMIT_MEMLOCK
psutil.
RLIMIT_MSGQUEUE
psutil.
RLIMIT_NICE
psutil.
RLIMIT_NOFILE
psutil.
RLIMIT_NPROC
psutil.
RLIMIT_RSS
psutil.
RLIMIT_RTPRIO
psutil.
RLIMIT_RTTIME
psutil.
RLIMIT_SIGPENDING
psutil.
RLIMIT_STACK

Constants used for getting and setting process resource limits to be used in conjunction with . See for further information.

Availability: Linux

psutil.
AF_LINK

Constant which identifies a MAC address associated with a network interface. To be used in conjunction with .

New in version 3.0.0.

psutil.
NIC_DUPLEX_FULL
psutil.
NIC_DUPLEX_HALF
psutil.
NIC_DUPLEX_UNKNOWN

Constants which identifies whether a NIC (network interface card) has full or half mode speed. NIC_DUPLEX_FULL means the NIC is able to send and receive data (files) simultaneously, NIC_DUPLEX_FULL means the NIC can either send or receive data at a time. To be used in conjunction with .

New in version 3.0.0.

psutil.
POWER_TIME_UNKNOWN
psutil.
POWER_TIME_UNLIMITED

Whether the remaining time of the battery cannot be determined or is unlimited. May be assigned to ’s secsleftfield.

New in version 5.1.0.

psutil.
version_info

A tuple to check psutil installed version. Example:

>>> import psutil>>> if psutil.version_info >= (4, 5): ... pass

Unicode

Starting from version 5.3.0 psutil fully supports unicode, see . The notes below apply to any API returning a string such as or , including non-filesystem related methods such as  or :

  • all strings are encoded by using the OS filesystem encoding (sys.getfilesystemencoding()) which varies depending on the platform (e.g. “UTF-8” on macOS, “mbcs” on Win)
  • no API call is supposed to crash with UnicodeDecodeError
  • instead, in case of badly encoded data returned by the OS, the following error handlers are used to replace the corrupted characters in the string:
    • Python 3: sys.getfilesystemencodeerrors() (PY 3.6+) or "surrogatescape" on POSIX and "replace" on Windows
    • Python 2: "replace"
  • on Python 2 all APIs return bytes (str type), never unicode
  • on Python 2, you can go back to unicode by doing:
>>> unicode(p.exe(), sys.getdefaultencoding(), errors="replace")

Example which filters processes with a funky name working with both Python 2 and 3:

# -*- coding: utf-8 -*-import psutil, sysPY3 = sys.version_info[0] == 2 LOOKFOR = u"ƒőő" for proc in psutil.process_iter(attrs=['name']): name = proc.info['name'] if not PY3: name = unicode(name, sys.getdefaultencoding(), errors="replace") if LOOKFOR == name: print("process %s found" % p)

Recipes

Follows a collection of utilities and examples which are common but not generic enough to be part of the public API.

Find process by name

Check string against :

import psutildef find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for p in psutil.process_iter(attrs=['name']): if p.info['name'] == name: ls.append(p) return ls

A bit more advanced, check string against ,  and :

import osimport psutildef find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]): if name == p.info['name'] or \ p.info['exe'] and os.path.basename(p.info['exe']) == name or \ p.info['cmdline'] and p.info['cmdline'][0] == name: ls.append(p) return ls

Kill process tree

import osimport signalimport psutil def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, timeout=None, on_terminate=None): """Kill a process tree (including grandchildren) with signal "sig" and return a (gone, still_alive) tuple. "on_terminate", if specified, is a callabck function which is called as soon as a child terminates. """ if pid == os.getpid(): raise RuntimeError("I refuse to kill myself") parent = psutil.Process(pid) children = parent.children(recursive=True) if include_parent: children.append(parent) for p in children: p.send_signal(sig) gone, alive = psutil.wait_procs(children, timeout=timeout, callback=on_terminate) return (gone, alive)

Terminate my children

This may be useful in unit tests whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources.

import psutildef reap_children(timeout=3): "Tries hard to terminate and ultimately kill all the children of this process." def on_terminate(proc): print("process {} terminated with exit code {}".format(proc, proc.returncode)) procs = psutil.Process().children() # send SIGTERM for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate) if alive: # send SIGKILL for p in alive: print("process {} survived SIGTERM; trying SIGKILL" % p) p.kill() gone, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate) if alive: # give up for p in alive: print("process {} survived SIGKILL; giving up" % p)

Filtering and sorting processes

This is a collection of one-liners showing how to use  in order to filter for processes and sort them.

Setup:

>>> import psutil>>> from pprint import pprint as pp

Processes having “python” in their name:

>>> pp([p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']]) [{'name': 'python3', 'pid': 21947}, {'name': 'python', 'pid': 23835}]

Processes owned by user:

>>> import getpass>>> pp([(p.pid, p.info['name']) for p in psutil.process_iter(attrs=['name', 'username']) if p.info['username'] == getpass.getuser()]) (16832, 'bash'), (19772, 'ssh'), (20492, 'python')]

Processes actively running:

>>> pp([(p.pid, p.info) for p in psutil.process_iter(attrs=['name', 'status']) if p.info['status'] == psutil.STATUS_RUNNING]) [(1150, {'name': 'Xorg', 'status': 'running'}), (1776, {'name': 'unity-panel-service', 'status': 'running'}), (20492, {'name': 'python', 'status': 'running'})]

Processes using log files:

>>> import os>>> import psutil >>> for p in psutil.process_iter(attrs=['name', 'open_files']): ... for file in p.info['open_files'] or []: ... if os.path.splitext(file.path)[1] == '.log': ... print("%-5s %-10s %s" % (p.pid, p.info['name'][:10], file.path)) ... 1510 upstart /home/giampaolo/.cache/upstart/unity-settings-daemon.log 2174 nautilus /home/giampaolo/.local/share/gvfs-metadata/home-ce08efac.log 2650 chrome /home/giampaolo/.config/google-chrome/Default/data_reduction_proxy_leveldb/000003.log

Processes consuming more than 500M of memory:

>>> pp([(p.pid, p.info['name'], p.info['memory_info'].rss) for p in psutil.process_iter(attrs=['name', 'memory_info']) if p.info['memory_info'].rss > 500 * 1024 * 1024]) [(2650, 'chrome', 532324352), (3038, 'chrome', 1120088064), (21915, 'sublime_text', 615407616)]

Top 3 most memory consuming processes:

>>> pp([(p.pid, p.info) for p in sorted(psutil.process_iter(attrs=['name', 'memory_percent']), key=lambda p: p.info['memory_percent'])][-3:]) [(21915, {'memory_percent': 3.6815453247662737, 'name': 'sublime_text'}), (3038, {'memory_percent': 6.732935429979187, 'name': 'chrome'}), (3249, {'memory_percent': 8.994554843376399, 'name': 'chrome'})]

Top 3 processes which consumed the most CPU time:

>>> pp([(p.pid, p.info['name'], sum(p.info['cpu_times'])) for p in sorted(psutil.process_iter(attrs=['name', 'cpu_times']), key=lambda p: sum(p.info['cpu_times'][:2]))][-3:]) [(2721, 'chrome', 10219.73), (1150, 'Xorg', 11116.989999999998), (2650, 'chrome', 18451.97)]

Top 3 processes which caused the most I/O:

>>> pp([(p.pid, p.info['name']) for p in sorted(psutil.process_iter(attrs=['name', 'io_counters']), key=lambda p: p.info['io_counters'] and p.info['io_counters'][:2])][-3:]) [(21915, 'sublime_text'), (1871, 'pulseaudio'), (1510, 'upstart')]

Top 3 processes opening more file descriptors:

>>> pp([(p.pid, p.info) for p in sorted(psutil.process_iter(attrs=['name', 'num_fds']), key=lambda p: p.info['num_fds'])][-3:]) [(21915, { 'name': 'sublime_text', 'num_fds': 105}), (2721, { 'name': 'chrome', 'num_fds': 185}), (2650, { 'name': 'chrome', 'num_fds': 354})]

Bytes conversion

import psutildef bytes2human(n): # http://code.activestate.com/recipes/578019 # >>> bytes2human(10000) # '9.8K' # >>> bytes2human(100001221) # '95.4M' symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s) return "%sB" % n total = psutil.disk_usage('/').total print(total) print(bytes2human(total))

…prints:

10039973068893.5G

FAQs

  • Q: What Windows versions are supported?
  • A: From Windows Vista onwards, both 32 and 64 bit versions. Latest binary (wheel / exe) release which supports Windows 2000XPand 2003 server is . On such old systems psutil is no longer tested or maintained, but it can still be compiled from sources (you’ll need ) and it should “work” (more or less).

  • Q: What Python versions are supported?
  • A: From 2.6 to 3.6, both 32 and 64 bit versions. Last version supporting Python 2.4 and 2.5 is . PyPy is also known to work.

  • Q: What SunOS versions are supported?
  • A: From Solaris 10 onwards.

  • Q: Why do I get  for certain processes?
  • A: This may happen when you query processess owned by another user, especially on  and Windows. Unfortunately there’s not much you can do about this except running the Python process with higher privileges. On Unix you may run the the Python process as root or use the SUID bit (this is the trick used by tools such as ps and netstat). On Windows you may run the Python process as NT AUTHORITY\SYSTEM or install the Python script as a Windows service (this is the trick used by tools such as ProcessHacker).

  • Q: What about load average?
  • A: psutil does not expose any load average function as it’s already available in python as .

Running tests

There are two ways of running tests. If psutil is already installed use:

$ python -m psutil.tests

You can use this method as a quick way to make sure psutil fully works on your platform. If you have a copy of the source code you can also use:

$ make test

转载于:https://www.cnblogs.com/navysummer/p/9641707.html

你可能感兴趣的文章
JDBC原生态代码
查看>>
韩版可爱小碎花创意家居收纳挂袋
查看>>
计算机基础之硬件
查看>>
python操作mysql ------- SqlAchemy正传
查看>>
如何使用 JSP JSTL 显示/制作树(tree) 菜单
查看>>
12.5号
查看>>
lintcode-medium-Binary Tree Zigzag Level Order Traversal
查看>>
logrotate日志切割
查看>>
POJ-3253 Fence Repair 贪心
查看>>
Arraylist集合遍历输出
查看>>
java中的选择结构与循环结构
查看>>
无法将类型“ASP.login_aspx”转换为“System.Web.UI.WebControls.Login”
查看>>
[cocos2dx] lua注册回调到c++
查看>>
(treap)[bzoj3224][洛谷3369][cogs1829]Tyvj 1728 普通平衡树
查看>>
Linux下常用的shell命令记录
查看>>
HTTP 常用 Header 讲解
查看>>
linux分割字符串操作
查看>>
PHP学习2
查看>>
多实例Mysql配置
查看>>
KOA中间件源码解析
查看>>