Psutil Readthedocs Io en Latest
Psutil Readthedocs Io en Latest
Release 5.9.5
Giampaolo Rodola
1 Quick links 1
2 About 3
3 Funding 5
3.1 Sponsors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Supporters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4 Install 7
6 Processes 23
6.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.2 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.3 Process class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7 Windows services 41
8 Constants 43
8.1 Operating system constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
8.2 Process status constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.3 Process priority constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.4 Process resources constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
8.5 Connections constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8.6 Hardware constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
9 Recipes 49
9.1 Find process by name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
9.2 Kill process tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.3 Filtering and sorting processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.4 Bytes conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
i
10 FAQs 53
11 Running tests 55
12 Debug mode 57
13 Security 59
14 Development guide 61
16 Timeline 65
Index 71
ii
CHAPTER 1
Quick links
• Home page
• Install
• Forum
• Download
• Blog
• Contributing
• Development guide
• What’s new
1
psutil Documentation, Release 5.9.5
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 monitoring,
profiling, limiting 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, OpenBSD, NetBSD
• Sun Solaris
• AIX
Supported Python versions are 2.7 and 3.4+. PyPy is also known to work.
The psutil documentation you’re reading is distributed as a single HTML page.
3
psutil Documentation, Release 5.9.5
4 Chapter 2. About
CHAPTER 3
Funding
While psutil is free software and will always be, the project would benefit immensely from some funding. Keeping up
with bug reports and maintenance has become hardly sustainable for me alone in terms of time. If you’re a company
that’s making significant use of psutil you can consider becoming a sponsor via GitHub, Open Collective or PayPal
and have your logo displayed in here and psutil doc.
3.1 Sponsors
3.2 Supporters
5
psutil Documentation, Release 5.9.5
6 Chapter 3. Funding
CHAPTER 4
Install
7
psutil Documentation, Release 5.9.5
8 Chapter 4. Install
CHAPTER 5
5.1 CPU
psutil.cpu_times(percpu=False)
Return system CPU times as a named tuple. Every attribute represents the seconds the CPU has spent in the
given mode. The attributes availability varies depending on the platform:
• user: time spent by normal processes executing in user mode; on Linux this also includes guest time
• system: time spent by processes executing in kernel mode
• idle: time spent doing nothing
Platform-specific fields:
• nice (UNIX): time spent by niced (prioritized) processes executing in user mode; on Linux this also in-
cludes guest_nice time
• iowait (Linux): time spent waiting for I/O to complete. This is not accounted in idle time counter.
• irq (Linux, BSD): time spent for servicing hardware interrupts
• softirq (Linux): time spent for servicing software interrupts
• steal (Linux 2.6.11+): time spent by other operating systems running in a virtualized environment
• guest (Linux 2.6.24+): time spent running a virtual CPU for guest operating systems under the control of
the Linux kernel
• guest_nice (Linux 3.2.0+): time spent running a niced guest (virtual CPU for guest operating systems
under the control of the Linux kernel)
• interrupt (Windows): time spent for servicing hardware interrupts ( similar to “irq” on UNIX)
• dpc (Windows): time spent servicing deferred procedure calls (DPCs); DPCs are interrupts that run at a
lower priority than standard interrupts.
9
psutil Documentation, Release 5.9.5
When percpu is True return a list of named tuples for each logical CPU on the system. 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.
Example output on Linux:
>>> import psutil
>>> psutil.cpu_times()
scputimes(user=17411.7, nice=77.99, system=3797.02, idle=51266.57, iowait=732.58,
˓→irq=0.01, softirq=142.43, steal=0.0, guest=0.0, guest_nice=0.0)
Warning: CPU times are always supposed to increase over time, or at least remain the same, and that’s
because time cannot go backwards. Surprisingly sometimes this might not be the case (at least on Windows
and Linux), see #1210.
psutil.cpu_percent(interval=None, percpu=False)
Return 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. 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 it
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.
>>> import psutil
>>> # blocking
>>> psutil.cpu_percent(interval=1)
2.0
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=None)
2.9
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]
>>>
Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless
0.0 value which you are supposed to ignore.
psutil.cpu_times_percent(interval=None, percpu=False)
Same as cpu_percent() but provides utilization percentages for each specific CPU time as is returned
by psutil.cpu_times(percpu=True). interval and percpu arguments have the same meaning as
in cpu_percent(). On Linux “guest” and “guest_nice” percentages are not accounted in “user” and
“user_nice” percentages.
Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless
0.0 value which you are supposed to ignore.
Changed in version 4.1.0: two new interrupt and dpc fields are returned on Windows.
psutil.cpu_count(logical=True)
Return the number of logical CPUs in the system (same as os.cpu_count in Python 3.4) or None if undeter-
mined. “logical CPUs” means the number of physical cores multiplied by the number of threads that can run
on each core (this is known as Hyper Threading). If logical is False return the number of physical cores only,
or None if undetermined. On OpenBSD and NetBSD psutil.cpu_count(logical=False) always
return None. Example on a system having 2 cores + Hyper Threading:
Note that psutil.cpu_count() may not necessarily be equivalent to the actual number of CPUs the current
process can use. That can vary in case process CPU affinity has been changed, Linux cgroups are being used or
(in case of Windows) on systems using processor groups or having more than 64 CPUs. The number of usable
CPUs can be obtained with:
>>> len(psutil.Process().cpu_affinity())
1
psutil.cpu_stats()
Return various CPU statistics as a named tuple:
• ctx_switches: number of context switches (voluntary + involuntary) since boot.
• interrupts: number of interrupts since boot.
• soft_interrupts: number of software interrupts since boot. Always set to 0 on Windows and SunOS.
• syscalls: number of system calls since boot. Always set to 0 on Linux.
Example (Linux):
5.1. CPU 11
psutil Documentation, Release 5.9.5
5.2 Memory
psutil.virtual_memory()
Return statistics about system memory usage as a named tuple including the following fields, expressed in bytes.
Main metrics:
• total: total physical memory (exclusive swap).
• 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.
Other metrics:
• used: memory used, calculated differently depending on the platform and designed for informational
purposes only. total - free does not necessarily match used.
• 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). total - used does not necessarily match free.
• 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 (Linux, BSD): cache for things like file system metadata.
• cached (Linux, BSD): cache for various things.
• shared (Linux, BSD): memory that may be simultaneously accessed by multiple processes.
• slab (Linux): in-kernel data structures cache.
• wired (BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.
The sum of used and available does not necessarily equal total. On Windows available and free are the same.
See meminfo.py script providing an example on how to convert bytes in a human readable form.
Note: if you just want to know how much physical memory is left in a cross platform fashion simply rely on
the available field.
>>>
>>> THRESHOLD = 100 * 1024 * 1024 # 100MB
>>> if mem.available <= THRESHOLD:
... print("warning")
...
>>>
Changed in version 5.2.3: on Linux this function relies on /proc fs instead of sysinfo() syscall so that it can be
used in conjunction with psutil.PROCFS_PATH in order to retrieve memory info about Linux containers
such as Docker and Heroku.
5.3 Disks
psutil.disk_partitions(all=False)
Return all mounted disk partitions as a list of named tuples including device, mount point and filesystem type,
similarly to “df” command on UNIX. If all parameter is False it tries to distinguish and return physical
devices only (e.g. hard disks, cd-rom drives, USB keys) and ignore all others (e.g. pseudo, memory, duplicate,
inaccessible filesystems). Note that this may not be fully reliable on all systems (e.g. on BSD this parameter
5.3. Disks 13
psutil Documentation, Release 5.9.5
is ignored). See disk_usage.py script providing an example usage. Returns a list of named tuples with the
following fields:
• device: the device path (e.g. "/dev/hda1"). On Windows this is the drive letter (e.g. "C:\\").
• mountpoint: the mount point path (e.g. "/"). On Windows this is the drive letter (e.g. "C:\\").
• fstype: the partition filesystem (e.g. "ext3" on UNIX or "NTFS" on Windows).
• opts: a comma-separated string indicating different mount options for the drive/partition. Platform-
dependent.
• maxfile: the maximum length a file name can have.
• maxpath: the maximum length a path name (directory name + base file name) can have.
Note: UNIX usually reserves 5% of the total disk space for the root user. total and used fields on UNIX refer to
the overall total and used space, whereas free represents the space available for the user and percent represents
the user utilization (see source code). That is why percent value may look 5% bigger than what you would
expect it to be. Also note that both 4 values match “df” cmdline utility.
Changed in version 4.3.0: percent value takes root reserved space into account.
psutil.disk_io_counters(perdisk=False, nowrap=True)
Return system-wide disk I/O statistics as a named tuple 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
Platform-specific fields:
• read_time: (all except NetBSD and OpenBSD) time spent reading from disk (in milliseconds)
• write_time: (all except NetBSD and OpenBSD) time spent writing to disk (in milliseconds)
• busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in milliseconds)
• read_merged_count (Linux): number of merged reads (see iostats doc)
>>>
>>> psutil.disk_io_counters(perdisk=True)
{'sda1': sdiskio(read_count=920, write_count=1, read_bytes=2933248, write_
˓→bytes=512, read_time=6016, write_time=4),
Note: on Windows "diskperf -y" command may need to be executed first otherwise this function won’t
find any disk.
Changed in version 5.3.0: numbers no longer wrap (restart from zero) across calls thanks to new nowrap argu-
ment.
Changed in version 4.0.0: added busy_time (Linux, FreeBSD), read_merged_count and write_merged_count
(Linux) fields.
Changed in version 4.0.0: NetBSD no longer has read_time and write_time fields.
5.4 Network
psutil.net_io_counters(pernic=False, nowrap=True)
Return system-wide network I/O statistics as a named tuple including the following attributes:
• bytes_sent: number of bytes sent
• bytes_recv: number of bytes received
• packets_sent: number of packets sent
• packets_recv: number of packets received
• errin: total number of errors while receiving
• errout: total number of errors while sending
• dropin: total number of incoming packets which were dropped
• dropout: total number of outgoing packets which were dropped (always 0 on macOS and BSD)
If pernic is True return the same information for every network interface installed on the system as a dictionary
with network interface names as the keys and the named tuple described above as the values. On some systems
5.4. Network 15
psutil Documentation, Release 5.9.5
such as Linux, on a very busy or long-lived system, the numbers returned by the kernel may overflow and wrap
(restart from zero). If nowrap is True psutil will detect and adjust those numbers across function calls and add
“old value” to “new value” so that the returned numbers will always be increasing or remain the same, but never
decrease. net_io_counters.cache_clear() can be used to invalidate the nowrap cache. On machines
with no network interfaces this function will return None or {} if pernic is True.
>>>
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=547971, bytes_recv=547971, packets_sent=5075, packets_
˓→recv=5075, errin=0, errout=0, dropin=0, dropout=0),
On macOS and AIX this function requires root privileges. To get per-process connections use Process.
connections(). Also, see netstat.py example script. Example:
˓→ status='ESTABLISHED', pid=None),
˓→ status='SYN_SENT', pid=None)
...]
Note: (macOS and AIX) psutil.AccessDenied is always raised unless running as root. This is a limita-
tion of the OS and lsof does the same.
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.
5.4. Network 17
psutil Documentation, Release 5.9.5
˓→broadcast=None, ptp=None),
>>>
Note: if you’re interested in others families (e.g. AF_BLUETOOTH) you can use the more powerful netifaces
extension.
Note: you can have more than one address of the same family associated with each interface (that’s why dict
values are lists).
Note: broadcast and ptp are not supported on Windows and are always None.
5.5 Sensors
psutil.sensors_temperatures(fahrenheit=False)
Return hardware temperatures. Each entry is a named tuple representing a certain hardware temperature 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. If sensors are not supported by the OS an empty dict
is returned. Example:
5.5. Sensors 19
psutil Documentation, Release 5.9.5
psutil.sensors_battery()
Return battery status information as a named tuple including the following values. If no battery is installed or
metrics can’t be determined None is returned.
• percent: battery power left as a percentage.
• secsleft: a rough approximation of how many seconds are left before the battery runs out of power. If the
AC power cable is connected this is set to psutil.POWER_TIME_UNLIMITED. If it can’t be deter-
mined it is set to psutil.POWER_TIME_UNKNOWN .
• power_plugged: True if the AC power cable is connected, False if not or None if it can’t be deter-
mined.
Example:
psutil.boot_time()
Return the system boot time expressed in seconds since the epoch. Example:
'2014-01-12 22:51:00'
Note: on Windows this function may return a time which is off by 1 second if it’s used across different processes
(see issue #1007).
psutil.users()
Return users currently connected on the system as a list of named tuples including the following fields:
• name: the name of the user.
• terminal: the tty or pseudo-tty associated with the user, if any, else None.
• 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.
• pid: the PID of the login process (like sshd, tmux, gdm-session-worker, . . . ). On Windows and OpenBSD
this is always set to None.
Example:
Processes
6.1 Functions
psutil.pids()
Return a sorted list of current running PIDs. To iterate over all processes and avoid race conditions
process_iter() should be preferred.
23
psutil Documentation, Release 5.9.5
import psutil
def 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()
6.2 Exceptions
class psutil.Error
Base exception class. All other exceptions inherit from this one.
class psutil.NoSuchProcess(pid, name=None, msg=None)
Raised by Process 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
Process.name() was previously called.
class psutil.ZombieProcess(pid, name=None, ppid=None, msg=None)
This may be raised by Process class methods when querying a zombie process on UNIX (Windows doesn’t
24 Chapter 6. Processes
psutil Documentation, Release 5.9.5
have zombie processes). name and ppid attributes are available if Process.name() or Process.ppid()
methods were called before the process turned into a zombie.
Note: this is a subclass of NoSuchProcess so if you’re not interested in retrieving zombies (e.g. when using
process_iter()) you can ignore this exception and just catch NoSuchProcess.
class psutil.Process(pid=None)
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. On Linux pid can also refer to a thread ID (the id field returned by
threads() method). When accessing methods of this class always be prepared to catch NoSuchProcess
and AccessDenied exceptions. hash 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 + creation time). As such it can
also be used with set.
Note: In order to efficiently fetch more than one information about the process at the same time, make sure to
use either oneshot() context manager or as_dict() utility method.
Note: the way this class is bound to a process is uniquely via its PID. That means that if the process ter-
minates 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:
nice() (set), ionice() (set), cpu_affinity() (set), rlimit() (set), children(), parent(),
parents(), suspend() resume(), send_signal(), terminate() kill(). To prevent this prob-
lem for all other methods you can use is_running() before querying the process or process_iter() in
case you’re iterating over all processes. It must be noted though that unless you deal with very “old” (inactive)
Process 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. name(), ppid(), uids(), create_time(), . . . )
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 name())
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:
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 empty 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).
26 Chapter 6. Processes
psutil Documentation, Release 5.9.5
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
˓→usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/
˓→'seat0'}
Note: on macOS Big Sur this function returns something meaningful only for the current process or in
other specific circumstances).
'2011-03-05 18:03:52'
as_dict(attrs=None, ad_value=None)
Utility method retrieving multiple process information as a dictionary. If attrs is specified it
must be a list of strings reflecting available Process class’s attribute names. Here’s a list of
possible string values: 'cmdline', 'connections', 'cpu_affinity', 'cpu_num',
'cpu_percent', 'cpu_times', 'create_time', 'cwd', 'environ', 'exe',
'gids', 'io_counters', 'ionice', 'memory_full_info', 'memory_info',
'memory_maps', 'memory_percent', 'name', 'nice', 'num_ctx_switches',
'num_fds', 'num_handles', 'num_threads', 'open_files', 'pid', 'ppid',
'status', 'terminal', 'threads', 'uids', 'username'`. If attrs argument is not
passed all public read only attributes are assumed. ad_value is the value which gets assigned to a dict
key in case AccessDenied or ZombieProcess exception is raised when retrieving that particular
process information. Internally, as_dict() uses oneshot() context manager so there’s no need you
use it also.
Changed in version 3.0.0: ad_value is used also when incurring into ZombieProcess exception, not
only AccessDenied
Changed in version 4.5.0: as_dict() is considerably faster thanks to oneshot() context manager.
28 Chapter 6. Processes
psutil Documentation, Release 5.9.5
parent()
Utility method which returns the parent process as a Process object, preemptively checking whether PID
has been reused. If no parent PID is known return None. See also ppid() and parents() methods.
parents()
Utility method which return the parents of this process as a list of Process instances. If no parents are
known return an empty list. See also ppid() and parent() methods.
New in version 5.6.0.
status()
The current process status as a string. The returned string is one of the psutil.STATUS_* constants.
cwd()
The process current working directory as an absolute path.
Changed in version 5.6.4: added support for NetBSD
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 os.getresuid 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 os.getresgid
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 niceness (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.
Starting from Python 3.3 this functionality is also available as os.getpriority and os.setpriority (see BPO-
10784). On Windows this is implemented via GetPriorityClass and SetPriorityClass Windows APIs and
value is one of the psutil.*_PRIORITY_CLASS constants reflecting the MSDN documentation. Ex-
ample which increases process priority on Windows:
>>> p.nice(psutil.HIGH_PRIORITY_CLASS)
ionice(ioclass=None, value=None)
Get or set process I/O niceness (priority). If no argument is provided it acts as a get, returning a
(ioclass, value) tuple on Linux and a ioclass integer on Windows. If ioclass is provided it acts as
a set. In this case an additional value can be specified on Linux only in order to increase or decrease the
I/O priority even further. Here’s the possible platform-dependent ioclass values.
Linux (see ioprio_get manual):
• IOPRIO_CLASS_RT: (high) the process gets first access to the disk every time. Use it with care as
it can starve the entire system. Additional priority level can be specified and ranges from 0 (highest)
to 7 (lowest).
• IOPRIO_CLASS_BE: (normal) the default for any process that hasn’t set a specific I/O priority.
Additional priority level ranges from 0 (highest) to 7 (lowest).
• IOPRIO_CLASS_IDLE: (low) get I/O time when no-one else needs the disk. No additional value is
accepted.
• IOPRIO_CLASS_NONE: returned when no priority was previously set.
Windows:
• IOPRIO_HIGH: highest priority.
• IOPRIO_NORMAL: default priority.
• IOPRIO_LOW: low priority.
• IOPRIO_VERYLOW: lowest priority.
Here’s an example on how to set the highest I/O priority depending on what platform you’re on:
30 Chapter 6. Processes
psutil Documentation, Release 5.9.5
• id: the native thread ID assigned by the kernel. If pid refers to the current process, this matches
the native_id attribute of the threading.Thread class, and can be used to reference individual Python
threads running within your own Python app.
• user_time: time spent in user mode.
• system_time: time spent in kernel mode.
cpu_times()
Return a named tuple representing the accumulated process times, in seconds (see explanation). This is
similar to os.times but can be used for any process PID.
• user: time spent in user mode.
• system: time spent in kernel mode.
• children_user: user time of all child processes (always 0 on Windows and macOS).
• children_system: system time of all child processes (always 0 on Windows and macOS).
• iowait: (Linux) time spent waiting for blocking I/O to complete. This value is excluded from user
and system times count (because the CPU is not doing any work).
Changed in version 4.1.0: return two extra fields: children_user and children_system.
Changed in version 5.6.4: added iowait on Linux.
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:
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
psutil.cpu_percent()). This means that a busy loop process running on a system with 2 logi-
32 Chapter 6. Processes
psutil Documentation, Release 5.9.5
cal 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. 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()))).
• rss: aka “Resident Set Size”, this is the non-swapped physical memory a process has used. On UNIX
it matches “top“‘s RES column). 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. 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).
• text (Linux, BSD): aka TRS (text resident set) the amount of memory devoted to executable code.
This matches “top“‘s CODE column).
• 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).
• 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.
Changed in version 4.0.0: multiple fields are returned, not only rss and vms.
memory_info_ex()
Same as memory_info() (deprecated).
34 Chapter 6. Processes
psutil Documentation, Release 5.9.5
memory_full_info()
This method returns the same information as memory_info(), plus, on some platform (Linux, macOS,
Windows), also provides additional metrics (USS, PSS and swap). The additional metrics provide a better
representation of “effective” process memory consumption (in case of USS) as explained in detail in this
blog post. 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. On platforms where extra fields are
not implemented this simply returns the same metrics as memory_info().
• 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:
>>>
˓→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,
...]
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 unit test. See also how to kill a process tree
and terminate my children.
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:
36 Chapter 6. Processes
psutil Documentation, Release 5.9.5
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 to determine the file handle name 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 issue 597).
Tools like ProcessHacker has the same limitation.
Warning: on BSD this method can return files with a null path (“”) due to a kernel bug, hence it’s not
reliable (see issue 595).
Example:
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) psutil.AccessDenied is always raised unless running as root (lsof does the same).
38 Chapter 6. Processes
psutil Documentation, Release 5.9.5
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 signal module constants) preemptively checking whether PID has been reused.
On UNIX this is the same as os.kill(pid, sig). On Windows only SIGTERM, CTRL_C_EVENT
and CTRL_BREAK_EVENT signals are supported and SIGTERM is treated as an alias for kill(). See
also how to kill a process tree and terminate my children.
Changed in version 3.2.0: support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals on Win-
dows 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 suspend-
ing 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
kill(). See also how to kill a process tree and terminate my children.
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
TerminateProcess. See also how to kill a process tree and terminate my children.
wait(timeout=None)
Wait for a process PID to terminate. The details about the return value differ on UNIX and Windows.
On UNIX: if the process terminated normally, the return value is a positive integer >= 0 indicating the exit
code. If the process was terminated by a signal return the negated value of the signal which caused the
termination (e.g. -SIGTERM). If PID is not a children of os.getpid (current process) just wait until the
process disappears and return None. If PID does not exist return None immediately.
On Windows: always return the exit code, which is a positive integer as returned by GetExitCodeProcess.
timeout is expressed in seconds. If specified and the process is still alive raise TimeoutExpired
exception. timeout=0 can be used in non-blocking apps: it will either return immediately or raise
TimeoutExpired.
The return value is cached. To wait for multiple processes use psutil.wait_procs().
40 Chapter 6. Processes
CHAPTER 7
Windows services
psutil.win_service_iter()
Return an iterator yielding a WindowsService 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 WindowsService instance. Raise psutil.NoSuchProcess
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 win_service_iter() and
win_service_get() 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 win_service_get()
to get a new WindowsService 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 Process class to control the service’s process.
41
psutil Documentation, Release 5.9.5
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:
Constants
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
43
psutil Documentation, Release 5.9.5
information about Linux containers such as Docker, Heroku or LXC (see here for more info). It must be noted
that this trick works only for APIs which rely on /proc filesystem (e.g. memory APIs and most Process 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.
44 Chapter 8. Constants
psutil Documentation, Release 5.9.5
Availability: Windows
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 psutil.Process.ionice() to get or set process I/O priority. IOPRIO_CLASS_NONE and IO-
PRIO_CLASS_BE (best effort) is the default for any process that hasn’t set a specific I/O priority. IO-
PRIO_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 ionice command line utility or ioprio_get system call.
Availability: Linux
psutil.IOPRIO_VERYLOW
psutil.IOPRIO_LOW
psutil.IOPRIO_NORMAL
psutil.IOPRIO_HIGH
A set of integers representing the I/O priority of a process on Windows. They can be used in conjunction with
psutil.Process.ionice() to get or set process I/O priority.
Availability: Windows
New in version 5.6.2.
Linux / FreeBSD:
psutil.RLIM_INFINITY
psutil.RLIMIT_AS
psutil.RLIMIT_CORE
psutil.RLIMIT_CPU
psutil.RLIMIT_DATA
psutil.RLIMIT_FSIZE
psutil.RLIMIT_MEMLOCK
psutil.RLIMIT_NOFILE
psutil.RLIMIT_NPROC
psutil.RLIMIT_RSS
psutil.RLIMIT_STACK
Linux specific:
psutil.RLIMIT_LOCKS
psutil.RLIMIT_MSGQUEUE
psutil.RLIMIT_NICE
psutil.RLIMIT_RTPRIO
psutil.RLIMIT_RTTIME
psutil.RLIMIT_SIGPENDING
FreeBSD specific:
psutil.RLIMIT_SWAP
psutil.RLIMIT_SBSIZE
psutil.RLIMIT_NPTS
Constants used for getting and setting process resource limits to be used in conjunction with psutil.Process.
rlimit(). See resource.getrlimit for further information.
Availability: Linux, FreeBSD
Changed in version 5.7.3: added FreeBSD support, added RLIMIT_SWAP, RLIMIT_SBSIZE, RLIMIT_NPTS.
46 Chapter 8. Constants
psutil Documentation, Release 5.9.5
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 psutil.net_if_stats().
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 psutil.
sensors_battery()’s secsleft field.
New in version 5.1.0.
psutil.version_info
A tuple to check psutil installed version. Example:
48 Chapter 8. Constants
CHAPTER 9
Recipes
import psutil
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(['name']):
if p.info['name'] == name:
ls.append(p)
return ls
A bit more advanced, check string against Process.name(), Process.exe() and Process.cmdline():
import os
import psutil
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(["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
49
psutil Documentation, Release 5.9.5
import os
import signal
import psutil
A collection of code samples showing how to use process_iter() to filter processes and sort them. Setup:
(16832, 'bash'),
(19772, 'ssh'),
(20492, 'python')]
50 Chapter 9. Recipes
psutil Documentation, Release 5.9.5
˓→3:])
import psutil
def 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:
100399730688
93.5G
52 Chapter 9. Recipes
CHAPTER 10
FAQs
53
psutil Documentation, Release 5.9.5
Running tests
$ python3 -m psutil.tests
55
psutil Documentation, Release 5.9.5
Debug mode
If you want to debug unusual situations or want to report a bug, it may be useful to enable debug mode via
PSUTIL_DEBUG environment variable. In this mode, psutil may (or may not) print additional information to stderr.
Usually these are error conditions which are not severe, and hence are ignored (instead of crashing). Unit tests auto-
matically run with debug mode enabled. On UNIX:
On Windows:
57
psutil Documentation, Release 5.9.5
Security
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
59
psutil Documentation, Release 5.9.5
Development guide
61
psutil Documentation, Release 5.9.5
63
psutil Documentation, Release 5.9.5
Timeline
65
psutil Documentation, Release 5.9.5
67
psutil Documentation, Release 5.9.5
p
psutil, 1
69
psutil Documentation, Release 5.9.5
B D
BELOW_NORMAL_PRIORITY_CLASS (in module psu- description() (psutil.WindowsService method), 42
til), 44 disk_io_counters() (in module psutil), 14
binpath() (psutil.WindowsService method), 41 disk_partitions() (in module psutil), 13
boot_time() (in module psutil), 20 disk_usage() (in module psutil), 14
BSD (in module psutil), 43 display_name() (psutil.WindowsService method), 41
C E
children() (psutil.Process method), 36 environ() (psutil.Process method), 27
cmdline() (psutil.Process method), 27 Error (class in psutil), 24
CONN_BOUND (in module psutil), 46 exe() (psutil.Process method), 26
CONN_CLOSE (in module psutil), 46
CONN_CLOSE_WAIT (in module psutil), 46 F
CONN_CLOSING (in module psutil), 46 FREEBSD (in module psutil), 43
CONN_DELETE_TCB (in module psutil), 46
CONN_ESTABLISHED (in module psutil), 46 G
CONN_FIN_WAIT1 (in module psutil), 46 getloadavg() (in module psutil), 12
CONN_FIN_WAIT2 (in module psutil), 46 gids() (psutil.Process method), 29
CONN_IDLE (in module psutil), 46
CONN_LAST_ACK (in module psutil), 46 H
CONN_LISTEN (in module psutil), 46 HIGH_PRIORITY_CLASS (in module psutil), 44
CONN_NONE (in module psutil), 46
CONN_SYN_RECV (in module psutil), 46 I
CONN_SYN_SENT (in module psutil), 46
IDLE_PRIORITY_CLASS (in module psutil), 44
CONN_TIME_WAIT (in module psutil), 46
io_counters() (psutil.Process method), 31
connections() (psutil.Process method), 37
ionice() (psutil.Process method), 29
cpu_affinity() (psutil.Process method), 33
IOPRIO_CLASS_BE (in module psutil), 45
cpu_count() (in module psutil), 10
IOPRIO_CLASS_IDLE (in module psutil), 45
cpu_freq() (in module psutil), 11
IOPRIO_CLASS_NONE (in module psutil), 45
cpu_num() (psutil.Process method), 33
IOPRIO_CLASS_RT (in module psutil), 45
71
psutil Documentation, Release 5.9.5
L R
LINUX (in module psutil), 43 REALTIME_PRIORITY_CLASS (in module psutil), 44
resume() (psutil.Process method), 39
M RLIM_INFINITY (in module psutil), 45
MACOS (in module psutil), 43 rlimit() (psutil.Process method), 30
memory_full_info() (psutil.Process method), 34 RLIMIT_AS (in module psutil), 45
memory_info() (psutil.Process method), 33 RLIMIT_CORE (in module psutil), 45
memory_info_ex() (psutil.Process method), 34 RLIMIT_CPU (in module psutil), 45
memory_maps() (psutil.Process method), 35 RLIMIT_DATA (in module psutil), 45
memory_percent() (psutil.Process method), 35 RLIMIT_FSIZE (in module psutil), 45
RLIMIT_LOCKS (in module psutil), 45
N RLIMIT_MEMLOCK (in module psutil), 45
RLIMIT_MSGQUEUE (in module psutil), 45
name() (psutil.Process method), 26
RLIMIT_NICE (in module psutil), 45
name() (psutil.WindowsService method), 41
RLIMIT_NOFILE (in module psutil), 45
net_connections() (in module psutil), 16
RLIMIT_NPROC (in module psutil), 45
net_if_addrs() (in module psutil), 17
RLIMIT_NPTS (in module psutil), 46
net_if_stats() (in module psutil), 18
RLIMIT_RSS (in module psutil), 45
net_io_counters() (in module psutil), 15
RLIMIT_RTPRIO (in module psutil), 45
NETBSD (in module psutil), 43
RLIMIT_RTTIME (in module psutil), 46
NIC_DUPLEX_FULL (in module psutil), 46
RLIMIT_SBSIZE (in module psutil), 46
NIC_DUPLEX_HALF (in module psutil), 47
RLIMIT_SIGPENDING (in module psutil), 46
NIC_DUPLEX_UNKNOWN (in module psutil), 47
RLIMIT_STACK (in module psutil), 45
nice() (psutil.Process method), 29
RLIMIT_SWAP (in module psutil), 46
NORMAL_PRIORITY_CLASS (in module psutil), 44
NoSuchProcess (class in psutil), 24 S
num_ctx_switches() (psutil.Process method), 31
num_fds() (psutil.Process method), 31 send_signal() (psutil.Process method), 39
num_handles() (psutil.Process method), 31 sensors_battery() (in module psutil), 19
num_threads() (psutil.Process method), 31 sensors_fans() (in module psutil), 19
sensors_temperatures() (in module psutil), 19
O start_type() (psutil.WindowsService method), 41
status() (psutil.Process method), 29
oneshot() (psutil.Process method), 25
status() (psutil.WindowsService method), 41
open_files() (psutil.Process method), 36
STATUS_DEAD (in module psutil), 44
OPENBSD (in module psutil), 43
STATUS_DISK_SLEEP (in module psutil), 44
OSX (in module psutil), 43
STATUS_IDLE (in module psutil), 44
STATUS_LOCKED (in module psutil), 44
P STATUS_PARKED (in module psutil), 44
parent() (psutil.Process method), 28 STATUS_RUNNING (in module psutil), 44
parents() (psutil.Process method), 29 STATUS_SLEEPING (in module psutil), 44
pid (psutil.Process attribute), 26 STATUS_STOPPED (in module psutil), 44
pid() (psutil.WindowsService method), 41 STATUS_SUSPENDED (in module psutil), 44
pid_exists() (in module psutil), 24 STATUS_TRACING_STOP (in module psutil), 44
pids() (in module psutil), 23 STATUS_WAITING (in module psutil), 44
Popen (class in psutil), 39 STATUS_WAKE_KILL (in module psutil), 44
72 Index
psutil Documentation, Release 5.9.5
T
terminal() (psutil.Process method), 29
terminate() (psutil.Process method), 39
threads() (psutil.Process method), 31
TimeoutExpired (class in psutil), 25
U
uids() (psutil.Process method), 29
username() (psutil.Process method), 29
username() (psutil.WindowsService method), 41
users() (in module psutil), 20
V
version_info (in module psutil), 47
virtual_memory() (in module psutil), 12
W
wait() (psutil.Process method), 39
wait_procs() (in module psutil), 24
win_service_get() (in module psutil), 41
win_service_iter() (in module psutil), 41
WINDOWS (in module psutil), 43
WindowsService (class in psutil), 41
Z
ZombieProcess (class in psutil), 24
Index 73