Note

psutil 8.0 introduces breaking API changes. See the migration guide if upgrading from 7.x.

API reference

Complete reference for all psutil classes and functions. Provided as a single HTML page for ease of searchability.

For a high-level overview with short examples see API overview.


Processes

Functions

psutil.pids()[source]

Return a sorted list of currently running PIDs. To iterate over all processes and avoid race conditions process_iter() is preferred, see Use process_iter() with an attrs list.

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

Changed in version 5.6.0: PIDs are returned in sorted order.

psutil.process_iter(attrs=None, ad_value=None)[source]

Return an iterator yielding a Process instance for all running processes. This should be preferred over psutil.pids() to iterate over processes, as retrieving info is safe from race conditions.

Every Process instance is only created once, and then cached for the next time psutil.process_iter() is called (if PID is still alive). Cache can optionally be cleared via process_iter.cache_clear().

attrs and ad_value have the same meaning as in Process.as_dict().

If attrs is specified, Process.as_dict() is called internally, and the results are cached so that subsequent method calls (e.g. p.name(), p.status()) return the cached values instead of issuing new system calls. See Process.attrs for a list of valid attrs names.

If a method raises AccessDenied during pre-fetch, it will return ad_value (default None) instead of raising.

Processes are returned sorted by PID.

>>> import psutil
>>> for proc in psutil.process_iter(['pid', 'name', 'username']):
...     print(proc.pid, proc.name(), proc.username())  # return cached values, never raise
...
1 systemd root
2 kthreadd root
3 ksoftirqd/0 root
...

All process attrs except slow ones:

>>> for p in psutil.process_iter(psutil.Process.attrs - {'memory_footprint', 'memory_maps'}):
...     print(p)

Clear internal cache:

>>> psutil.process_iter.cache_clear()

Note

since Process instances are reused across calls, a subsequent process_iter() call will overwrite or clear any previously pre-fetched values. Do not rely on cached values from a prior iteration.

Changed in version 5.3.0: added attrs and ad_value arguments.

Changed in version 6.0.0:

  • No longer checks whether each yielded process PID has been reused.

  • Added psutil.process_iter.cache_clear() API.

Changed in version 8.0.0:

  • When attrs is specified, the pre-fetched values are cached directly on the Process instance, so that subsequent method calls (e.g. p.name(), p.status()) return the cached values instead of making new system calls. The Process.info dict is deprecated in favor of this new approach.

  • Passing an empty list (attrs=[]) to mean “all attributes” is deprecated; use Process.attrs instead.

psutil.pid_exists(pid)[source]

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(procs, timeout=None, callback=None)[source]

Bulk operation that waits for a list of Process instances to terminate. Return a (gone, alive) tuple. The gone processes will have a new returncode attribute set by Process.wait().

callback is called with a Process instance whenever a process terminates.

Returns as soon as all processes terminate or timeout (seconds) expires. Unlike Process.wait(), it does not raise TimeoutExpired on timeout.

Typical usage:

  • send SIGTERM to a list of processes

  • wait a short time

  • send SIGKILL to any still alive

import psutil

def on_terminate(proc):
    print(f"{proc} terminated with exit code {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:
    print(f"{p} is still alive, send SIGKILL")
    p.kill()

Exceptions

exception psutil.Error

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

exception psutil.NoSuchProcess(pid, name=None, msg=None)

Raised by Process class or its methods when a process with the given pid is not found, no longer exists, or its PID has been reused. name attribute is set only if Process.name() was called before the process disappeared.

exception psutil.ZombieProcess(pid, name=None, ppid=None, msg=None)

Subclass of NoSuchProcess. Raised by Process methods when encountering a zombie process on UNIX (Windows does not have zombies). name and ppid attributes are set if Process.name() or Process.ppid() were called before the process became a zombie.

If you do not need to detect zombies, you can ignore this exception and just catch NoSuchProcess.

Added in version 3.0.0.

exception psutil.AccessDenied(pid=None, name=None, msg=None)

Raised by Process methods when an action is denied due to insufficient privileges. name is set if Process.name() was called before the exception was raised.

exception psutil.TimeoutExpired(seconds, pid=None, name=None, msg=None)

Raised by Process.wait() method if timeout expires and the process is still alive. name attribute is set if Process.name() was previously called.

Process class

class psutil.Process(pid=None)[source]

Represents an OS process with the given pid. If pid is omitted, the current process pid (os.getpid()) is used. Raises NoSuchProcess if pid does not exist.

On Linux, pid can also refer to a thread ID (the id field returned by threads()).

When calling methods of this class, always be prepared to catch NoSuchProcess and AccessDenied exceptions. The builtin hash() can be used on instances to uniquely identify a process over time (the hash combines PID and creation time), so instances can also be used in a set.

Note

This class is bound to a process via its PID. If the process terminates and the OS reuses its PID, you may accidentally interact with another process. To prevent this, use is_running() first. Some methods (e.g., setters and signal-related methods) perform an additional check using PID + creation time, and will raise NoSuchProcess if the PID has been reused. See PID reuse for details.

Note

To fetch multiple attributes efficiently, use the oneshot() context manager or the as_dict() utility method.

pid

The process PID as a read-only property.

attrs

A frozenset of strings representing the valid attribute names accepted by as_dict() and process_iter(). It defaults to all read-only Process method names, minus the utility methods such as as_dict(), children(), etc.

>>> import psutil
>>> psutil.Process.attrs
frozenset({'cmdline', 'cpu_num', 'cpu_percent', ...})
>>> # all attrs
>>> psutil.process_iter(attrs=psutil.Process.attrs)
>>> # all attrs except 'net_connections'
>>> psutil.process_iter(attrs=psutil.Process.attrs - {"net_connections"})

Added in version 8.0.0.

info

A dict containing pre-fetched process info, set by process_iter() when called with attrs argument. Accessing this attribute is deprecated and raises DeprecationWarning. Use method calls instead (e.g. p.name() instead of p.info['name']) or process_iter() + Process.as_dict() if you need a dict structure.

See also

migration guide.

Deprecated since version 8.0.0.

oneshot()[source]

Context manager that speeds up retrieval of multiple process attributes. Internally, many attributes (e.g. name(), ppid(), uids(), create_time(), …) share the same underlying system call; within this context, those calls are executed once and results are cached, avoiding redundant syscalls.

>>> import psutil
>>> p = psutil.Process()
>>> with p.oneshot():
...     p.name()  # actual syscall
...     p.cpu_times()  # from cache
...     p.create_time()  # from cache
...     p.ppid()  # from cache
...     p.status()  # from cache
...
>>>

Added in version 5.0.0.

name()[source]

The process name. On Windows the return value is cached after first call. Not on POSIX because the process name may change.

See also

how to find a process by name.

exe()[source]

The process executable as an absolute path. On some systems, if exe cannot be determined for some internal reason (e.g. system process or path no longer exists), this is an empty string. The return value is cached after first call.

>>> import psutil
>>> psutil.Process().exe()
'/usr/bin/python3'
cmdline()[source]

The command line used to start this process, as a list of strings. The return value is not cached because the cmdline of a process may change.

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

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', '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'}

Note

on macOS Big Sur this function returns something meaningful only for the current process or in other specific circumstances.

Added in version 4.0.0.

Changed in version 5.3.0: added SunOS support.

Changed in version 5.6.3: added AIX support.

Changed in version 5.7.3: added BSD support.

create_time()[source]

The process creation time as a floating point number expressed in seconds since the epoch (seconds since January 1, 1970, at midnight UTC). The return value, which is cached after first call, is based on the system clock, which means it is affected by changes such as manual adjustments or time synchronization (e.g. NTP).

>>> 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=None, ad_value=None)[source]

Utility method returning multiple process information as a dictionary.

If attrs is specified, it must be a collection of strings reflecting available Process class’s attribute names. If not passed all Process.attrs names 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 (default None).

The 'net_connections' attribute is retrieved by calling Process.net_connections() with kind="inet".

Internally, as_dict() uses oneshot() 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'}
>>> # all attrs except slow ones
>>> p.as_dict(attrs=p.attrs - {'memory_footprint', 'memory_maps'})
{'username': 'giampaolo', 'pid': 12366, 'name': 'python', ...}
>>>

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.

ppid()[source]

The process parent PID. On Windows the return value is cached after the first call. On POSIX it is not cached because it may change if the process becomes a zombie. See also parent() and parents() methods.

parent()[source]

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()[source]

Utility method which returns 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.

Added in version 5.6.0.

status()[source]

The current process status as a ProcessStatus enum member. The returned value is one of the STATUS_* constants. A common use case is detecting zombie processes (p.status() == psutil.STATUS_ZOMBIE).

Changed in version 8.0.0: return value is now a ProcessStatus enum member instead of a plain str. See migration guide.

cwd()[source]

The process current working directory as an absolute path. If it cannot be determined (e.g. a system process or directory no longer exists) it returns an empty string.

Changed in version 5.6.4: added support for NetBSD.

username()[source]

The name of the user that owns the process. On UNIX this is calculated by using the real process UID from uids().

uids()[source]

The real, effective and saved user ID 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()[source]

The real, effective and saved group ID 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()[source]

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)[source]

Get or set process niceness (priority). On UNIX this is a number which 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 lower priority
>>> p.nice()  # get
10
>>>

On Windows value is one of the *_PRIORITY_CLASS constants:

>>> p.nice(psutil.HIGH_PRIORITY_CLASS)  # set higher priority
>>> p.nice()  # get
<ProcessPriority.HIGH_PRIORITY_CLASS: 32768>

This method was later incorporated in Python 3.3 as os.getpriority() and os.setpriority() (see BPO-10784).

Changed in version 8.0.0: on Windows, the return value is now a ProcessPriority enum member. See migration guide.

ionice(ioclass=None, value=None)[source]

Get or set process I/O niceness (priority). Called with no arguments (get), returns a (ioclass, value) named tuple on Linux or an ioclass integer on Windows. Called with ioclass (one of the IOPRIO_* constants), sets the I/O priority. On Linux, an additional value ranging from 0 to 7 can be specified to further adjust the priority level specified by ioclass.

>>> import psutil
>>> p = psutil.Process()
>>> if psutil.LINUX:
...     p.ionice(psutil.IOPRIO_CLASS_RT, value=7)  # highest
... else:
...     p.ionice(psutil.IOPRIO_HIGH)
...
>>> p.ionice()  # get
pionice(ioclass=<ProcessIOPriority.IOPRIO_CLASS_RT: 1>, value=7)

Availability: Linux, Windows

Changed in version 5.6.2: Windows: accept new IOPRIO_* constants.

Changed in version 8.0.0: ioclass is now a ProcessIOPriority enum member. See migration guide.

rlimit(resource, limits=None)[source]

Get or set process resource limits. resource must be one of the RLIMIT_* constants. limits is an optional (soft, hard) tuple. If provided, the method sets the limits; if omitted, it returns the current (soft, hard) tuple. This is the same as stdlib resource.getrlimit() and resource.setrlimit(), but can be used for any process PID.

>>> import psutil
>>> p = psutil.Process()
>>> p.rlimit(psutil.RLIMIT_NOFILE, (128, 128))   # max 128 file descriptors
>>> p.rlimit(psutil.RLIMIT_FSIZE, (1024, 1024))  # max file size 1024 bytes
>>> p.rlimit(psutil.RLIMIT_FSIZE)                # get current limits of ...
(1024, 1024)

Availability: Linux, FreeBSD

Changed in version 5.7.3: added FreeBSD support.

io_counters()[source]

Return process I/O statistics. All fields are cumulative counters since process creation.

  • read_count: number of read syscalls (e.g., read(2), pread(2)).

  • write_count: number of write syscalls (e.g., write(2), pwrite(2)).

  • read_bytes: bytes read (-1 on BSD).

  • write_bytes: bytes written (-1 on BSD).

Linux specific:

  • read_chars (Linux): bytes read via read() and pread() syscalls. Unlike read_bytes, this includes tty I/O and counts bytes regardless of whether actual disk I/O occurred (e.g. reads served from page cache are included).

  • write_chars (Linux): bytes written via write() and pwrite() syscalls. Same caveats as read_chars.

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, Windows, BSD, AIX

Changed in version 5.2.0: Linux: added read_chars and write_chars fields.

Changed in version 5.2.0: Windows: added other_count and other_bytes fields.

num_ctx_switches()[source]

The number of context switches performed by this process as a (voluntary, involuntary) named tuple (cumulative counter).

Note

(Windows, macOS) involuntary value is always set to 0, while voluntary value reflects the total number of context switches (voluntary + involuntary). This is a limitation of the OS.

Changed in version 5.4.1: added AIX support.

num_fds()[source]

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()[source]

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

threads()[source]

Return a list of threads spawned by this process. On OpenBSD, root privileges are required. Each entry includes:

  • id: native thread ID assigned by the kernel. If pid refers to the current process, this matches threading.Thread.native_id, and can be used to reference individual Python threads in your app.

  • user_time: time spent in user mode.

  • system_time: time spent in kernel mode.

cpu_times()[source]

Return accumulated process CPU times as cumulative counters expressed in seconds. Same as os.times(), but works 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. (iowait). Excluded from user and system times count (because the CPU is idle).

>>> import psutil
>>> p = psutil.Process()
>>> p.cpu_times()
pcputimes(user=0.03, system=0.67, children_user=0.0, children_system=0.0, iowait=0.08)
>>> sum(p.cpu_times()[:2])  # cumulative, excluding children and iowait
0.70

Changed in version 4.1.0: added children_user and children_system fields.

Changed in version 5.6.4: Linux: added iowait field.

cpu_percent(interval=None)[source]

Return process CPU utilization as a percentage. Values can exceed 100.0 if the process runs multiple threads on different CPUs.

If interval is > 0.0, measures CPU times before and after the interval (blocking). If 0.0 or None, returns the utilization since the 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 method be called with at least 0.1 seconds between calls.

>>> 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 is not split evenly between all available CPUs (differently from psutil.cpu_percent()). To emulate Windows taskmgr.exe behavior: p.cpu_percent() / psutil.cpu_count().

cpu_affinity(cpus=None)[source]

Get or set process CPU affinity (the set of CPUs the process is allowed to run on). If no argument is passed, return the current affinity as a list of integers. If passed, cpus must be a list of CPU integers. An empty list sets affinity to all eligible CPUs.

>>> 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()[source]

Return what CPU this process is currently running on. The returned number should be <= psutil.cpu_count(). 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.

Availability: Linux, FreeBSD, SunOS

Added in version 5.1.0.

memory_info()[source]

Return memory information about the process. Fields vary by platform (all values in bytes). The portable fields available on all platforms are rss and vms.

Linux

macOS

BSD

Solaris

AIX

Windows

rss

rss

rss

rss

rss

rss

vms

vms

vms

vms

vms

vms

shared

text

text

data

data

stack

peak_rss

peak_rss

peak_vms

  • rss: aka RSS. On UNIX matches the top RES column. On Windows maps to WorkingSetSize.

  • vms: aka VMS. On UNIX matches the top VIRT column. On Windows maps to PrivateUsage (private committed pages only), which differs from the UNIX definition; use virtual from memory_info_ex() for the true virtual address space size.

  • shared (Linux): shared memory that could be shared with other processes (shared libraries, memory-mapped files). Counted even if no other process is currently mapping it. Matches top’s SHR column.

  • text (Linux, BSD): aka TRS (Text Resident Set). Resident memory devoted to executable code. This memory is read-only and typically shared across all processes running the same binary. Matches top’s CODE column.

  • data (Linux, BSD): aka DRS (Data Resident Set). On Linux this covers the data and stack segments combined (from /proc/pid/statm). On BSD it covers the data segment only (see stack). Matches top’s DATA column.

  • stack (BSD): size of the process stack segment. Reported separately from data (unlike Linux where both are combined).

  • peak_rss (BSD, Windows): see peak_rss. On BSD may be 0 for kernel PIDs. On Windows maps to PeakWorkingSetSize.

  • peak_vms (Windows): see peak_vms. Maps to PeakPagefileUsage.

For the full definitions of Windows fields see PROCESS_MEMORY_COUNTERS_EX.

Example on Linux:

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

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

Changed in version 8.0.0: (see migration guide)

  • Linux: lib and dirty removed (always 0 since Linux 2.6). Deprecated aliases returning 0 and emitting DeprecationWarning are kept.

  • macOS: removed pfaults and pageins fields with no backward-compatible aliases. Use page_faults() instead.

  • Windows: eliminated old aliases: wsetrss, peak_wsetpeak_rss, pagefile and privatevms, peak_pagefilepeak_vms, num_page_faultspage_faults() method. At the same time paged_pool, nonpaged_pool, peak_paged_pool, peak_nonpaged_pool were moved to memory_info_ex(). All these old names still work but raise DeprecationWarning.

  • BSD: added peak_rss field.

memory_info_ex()[source]

Extends memory_info() with additional platform-specific memory metrics (all values in bytes). On platforms where extra fields are not implemented this returns the same result as memory_info().

Linux

macOS

Windows

peak_rss

peak_rss

virtual

peak_vms

peak_virtual

rss_anon

rss_anon

paged_pool

rss_file

rss_file

nonpaged_pool

rss_shmem

wired

peak_paged_pool

swap

compressed

peak_nonpaged_pool

hugetlb

phys_footprint

  • peak_rss (Linux, macOS): see peak_rss.

  • peak_vms (Linux): see peak_vms.

  • rss_anon (Linux, macOS): resident anonymous memory (heap, stack, private mappings) not backed by any file. Set to 0 on Linux < 4.5.

  • rss_file (Linux, macOS): resident file-backed memory mapped from files (shared libraries, memory-mapped files). Set to 0 on Linux < 4.5.

  • rss_shmem (Linux): resident shared memory (tmpfs, shm_open). rss_anon + rss_file + rss_shmem equals rss. Set to 0 on Linux < 4.5.

  • wired (macOS): memory pinned in RAM by the kernel on behalf of this process; cannot be compressed or paged out.

  • swap (Linux): process memory currently in swap. Equivalent to memory_footprint().swap but cheaper, as it reads from /proc/pid/status instead of /proc/pid/smaps.

  • compressed (macOS): memory held in the in-RAM memory compressor; not counted in rss. A large value signals memory pressure but has not yet triggered swapping.

  • hugetlb (Linux): resident memory backed by huge pages. Set to 0 on Linux < 4.4.

  • phys_footprint (macOS): total physical memory impact including compressed memory. What Xcode and footprint(1) report; prefer this over rss macOS memory monitoring.

  • virtual (Windows): true virtual address space size, including reserved-but-uncommitted regions (unlike vms in memory_info()).

  • peak_virtual (Windows): peak virtual address space size.

  • paged_pool (Windows): kernel memory used for objects created by this process (open file handles, registry keys, etc.) that the OS may swap to disk under memory pressure.

  • nonpaged_pool (Windows): kernel memory used for objects that must stay in RAM at all times (I/O request packets, device driver buffers, etc.). A large or growing value may indicate a driver memory leak.

  • peak_paged_pool (Windows): peak paged-pool usage.

  • peak_nonpaged_pool (Windows): peak non-paged-pool usage.

For the full definitions of Windows fields see PROCESS_MEMORY_COUNTERS_EX.

Added in version 8.0.0.

memory_footprint()[source]

Return uss, pss and swap memory metrics. These give a more accurate picture of actual memory consumption than memory_info(). It walks the full process address space, so it is slower than memory_info() and may require elevated privileges.

  • uss (Linux, macOS, Windows): aka USS; the private memory of the process, which would be freed if the process were terminated right now.

  • pss (Linux): aka PSS; shared memory divided evenly among the processes sharing 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): process memory currently in swap, counted per-mapping.

Example on Linux:

>>> import psutil
>>> p = psutil.Process()
>>> p.memory_footprint()
pfootprint(uss=6545408, pss=6872064, swap=0)

Availability: Linux, macOS, Windows

Added in version 8.0.0.

memory_full_info()[source]

This deprecated method returns the same information as memory_info() plus memory_footprint() in a single named tuple.

Added in version 4.0.0.

Deprecated since version 8.0.0: use memory_footprint() instead. See migration guide.

memory_percent(memtype='rss')[source]

Return process memory usage as a percentage of total physical memory. Same as:

Process().memory_info().rss / virtual_memory().total * 100

memtype selects which memory field to use and can be any attribute from memory_info(), memory_info_ex(), or memory_footprint() (default is "rss").

Changed in version 4.0.0: added memtype parameter.

memory_maps(grouped=True)[source]

Return the process’s memory-mapped file regions as a list. Fields vary by platform (all values in bytes).

If grouped is True, regions with the same path are merged and their numeric fields summed. If grouped is False, each region is listed individually; the tuple also includes addr (address range) and perms (permission string, e.g., "r-xp").

Linux

Windows

FreeBSD

Solaris

rss

rss

rss

rss

size

private

anonymous

pss

ref_count

locked

shared_clean

shadow_count

shared_dirty

private_clean

private_dirty

referenced

anonymous

swap

Linux fields (from /proc/pid/smaps):

  • rss: RSS for this mapping.

  • size: total virtual size; may far exceed rss if parts have never been accessed.

  • pss: PSS for this mapping, that is rss split proportionally among all processes sharing it.

  • shared_clean: shared memory not written to since loaded (clean); can be discarded and reloaded from disk for free.

  • shared_dirty: shared memory that has been written to (dirty).

  • private_clean: private memory not written to (clean).

  • private_dirty: private memory that has been written to (dirty); must be saved to swap before it can be freed. The key indicator of real memory cost.

  • referenced: bytes recently accessed.

  • anonymous: anonymous memory in this mapping (heap, stack).

  • swap: bytes from this mapping currently in swap.

FreeBSD fields:

  • private: private memory in this mapping.

  • ref_count: reference count on the underlying memory object.

  • shadow_count: depth of the copy-on-write chain.

>>> 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),
 ...]

See also

scripts/pmap.py.

Availability: Linux, Windows, FreeBSD, SunOS

Changed in version 5.6.0: removed macOS support because inherently broken (see issue #1291)

children(recursive=False)[source]

Return the children of this process as a list of Process instances. If recursive is True, return all descendants. Pseudo-code example (assuming A is 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: if a process in the tree disappears (e.g., X), its descendants (Y) won’t be returned since the reference to the parent is lost. This concept is well illustrated by this unit test.

See also

how to kill a process tree.

page_faults()[source]

Return the number of page faults for this process as a (minor, major) named tuple. Both are cumulative counters since process creation.

>>> import psutil
>>> p = psutil.Process()
>>> p.page_faults()
ppagefaults(minor=5905, major=3)

Added in version 8.0.0.

open_files()[source]

Return regular files opened by process as a list. Each entry includes:

  • path: the absolute file name.

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

Linux only:

  • position (Linux): the file position (offset).

  • mode (Linux): a string indicating how the file was opened, similarly to open() builtin mode argument. Possible values are 'r', 'w', 'a', 'r+' and 'a+'. There’s no distinction between files opened in binary or text mode ("b" or "t").

  • flags (Linux): the flags which were passed to the underlying os.open() C call when the file was opened (e.g. os.O_RDONLY, os.O_TRUNC, 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

Changed in version 3.1.0: no longer hangs on Windows.

Changed in version 4.1.0: Linux: added position, mode and flags fields.

net_connections(kind='inet')[source]

Same as psutil.net_connections() but for this process only (the returned named tuples have no pid field). The kind parameter and the same limitations apply (root may be needed on some platforms).

>>> import psutil
>>> p = psutil.Process(1694)
>>> p.name()
'firefox'
>>> p.net_connections()
[pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status=<ConnectionStatus.CONN_ESTABLISHED: 'ESTABLISHED'>),
 pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status=<ConnectionStatus.CONN_CLOSING: 'CLOSING'>),
 pconn(fd=119, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status=<ConnectionStatus.CONN_ESTABLISHED: 'ESTABLISHED'>),
 pconn(fd=123, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status=<ConnectionStatus.CONN_SYN_SENT: 'SYN_SENT'>)]
connections()[source]

Same as net_connections() (deprecated).

Deprecated since version 6.0.0: use net_connections() instead.

is_running()[source]

Return whether the current process is running. Differently from psutil.pid_exists(p.pid), this is reliable also in case the process is gone and its PID reused by another process.

If PID has been reused, this method will also remove the process from process_iter() internal cache.

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

Changed in version 6.0.0: automatically remove process from process_iter() internal cache if PID has been reused by another process.

send_signal(sig)[source]

Send signal sig 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

Changed in version 3.2.0: Windows: add support for CTRL_C_EVENT and CTRL_BREAK_EVENT signals.

suspend()[source]

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.

resume()[source]

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.

terminate()[source]

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.

kill()[source]

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.

wait(timeout=None)[source]

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 an integer >= 0 indicating the exit code. If the process was terminated by a signal, returns the negated value of the signal which caused the termination (e.g. -SIGTERM). If PID is not a child of os.getpid() (current process), it just waits until the process disappears and return None. If PID does not exist return None immediately.

On Windows: always return the exit code via GetExitCodeProcess.

timeout is expressed in seconds. If specified, and the process is still alive, raise TimeoutExpired. 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().

>>> import psutil
>>> p = psutil.Process(9891)
>>> p.terminate()
>>> p.wait()
<NegSignal.SIGTERM: -15>

Note

when timeout is not None and the platform supports it, an efficient event-driven mechanism is used to wait for process termination:

If none of these mechanisms are available, the function falls back to a busy loop (non-blocking call and short sleeps).

Functionality also ported to the subprocess module in Python 3.15, see cpython/PR-144047.

Changed in version 5.7.2: if timeout is not None, use efficient event-driven implementation on Linux >= 5.3 and macOS / BSD.

Changed in version 5.7.1: return value is cached (instead of returning None).

Changed in version 5.7.1: POSIX: if the signal is negative, return it as a human readable enum.

Changed in version 7.2.2: on Linux >= 5.3 + Python >= 3.9 and macOS/BSD, use os.pidfd_open() and select.kqueue() respectively, instead of less efficient busy-loop polling.


Popen class

class psutil.Popen(*args, **kwargs)[source]

Same as subprocess.Popen, but in addition it provides all psutil.Process methods in a single class. For the following methods, which are common to both classes, psutil implementation takes precedence: send_signal(), terminate(), kill(). This is done to avoid killing another process if its PID has been reused, fixing BPO-6973.

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

Changed in version 4.4.0: added context manager support.


C heap introspection

The following functions provide direct access to the platform’s native heap allocator (such as glibc’s malloc on Linux or jemalloc on BSD). They are low-level interfaces intended for detecting memory leaks in C extensions, which are usually not revealed via standard RSS / VMS metrics. These functions do not reflect Python object memory; they operate solely on allocations made in C via malloc(3), free(3), and related calls.

The general idea behind these functions is straightforward: capture the state of the heap before and after repeatedly invoking a function implemented in a C extension, and compare the results. If heap_used or mmap_used grows steadily across iterations, the C code is likely retaining memory it should be releasing. This provides an allocator-level way to spot native leaks that Python’s memory tracking misses.

Tip

Check out psleak project to see a practical example of how these APIs can be used to detect memory leaks in C extensions.

psutil.heap_info()[source]

Return low-level heap statistics from the system’s C allocator. On Linux, this exposes uordblks and hblkhd fields from glibc mallinfo2(3).

  • heap_used: total number of bytes currently allocated via malloc() (small allocations).

  • mmap_used: total number of bytes currently allocated via mmap(2) or via large malloc() allocations. Always set to 0 on macOS.

  • heap_count: (Windows only) number of private heaps created via HeapCreate().

>>> import psutil
>>> psutil.heap_info()
pheap(heap_used=5177792, mmap_used=819200)

These fields reflect how unreleased C allocations affect the heap:

Platform

Allocation type

Affected field

UNIX / glibc

small malloc() ≤128KB without free()

heap_used

UNIX / glibc

large malloc() >128KB without free() , or mmap() without munmap()

mmap_used

Windows

HeapAlloc() without HeapFree()

heap_used

Windows

VirtualAlloc() without VirtualFree()

mmap_used

Windows

HeapCreate() without HeapDestroy()

heap_count

Availability: Linux with glibc, Windows, macOS, FreeBSD, NetBSD

Added in version 7.2.0.

psutil.heap_trim()[source]

Request that the underlying allocator free any unused memory it’s holding in the heap (typically small malloc() allocations).

In practice, modern allocators rarely comply, so this is not a general-purpose memory-reduction tool and won’t meaningfully shrink RSS in real programs. Its primary value is in leak detection tools.

Calling heap_trim() before taking measurements helps reduce allocator noise, giving you a cleaner baseline so that changes in heap_used come from the code you’re testing, not from internal allocator caching or fragmentation. Its effectiveness depends on allocator behavior and fragmentation patterns.

Availability: Linux with glibc, Windows, macOS, FreeBSD, NetBSD

Added in version 7.2.0.


Windows services

psutil.win_service_iter()

Return an iterator yielding WindowsService instances for all installed Windows services.

Added in version 4.2.0.

Availability: Windows

psutil.win_service_get(name)

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

Added 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’s 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 either '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.

status()

Service status as a string, which can 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.

>>> import psutil
>>> list(psutil.win_service_iter())
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
 <WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
 <WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
 <WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
 ...]
>>> 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'}

Availability: Windows

Added in version 4.2.0.


Constants

The following enum classes group related constants, and are useful for type annotations and introspection. The individual constants (e.g. STATUS_RUNNING) are also accessible directly from the psutil namespace as aliases for the enum members, and should be preferred over accessing them via the enum class (e.g. prefer psutil.STATUS_RUNNING over psutil.ProcessStatus.STATUS_RUNNING).

class psutil.ProcessStatus[source]

enum.StrEnum collection of STATUS_* constants. Returned by Process.status().

Added in version 8.0.0.

class psutil.ProcessPriority

enum.IntEnum collection of *_PRIORITY_CLASS constants for Process.nice() on Windows.

Availability: Windows

Added in version 8.0.0.

class psutil.ProcessIOPriority[source]

enum.IntEnum collection of I/O priority constants for Process.ionice().

IOPRIO_CLASS_* on Linux, IOPRIO_* on Windows.

Availability: Linux, Windows

Added in version 8.0.0.

class psutil.ProcessRlimit

enum.IntEnum collection of RLIMIT_* constants for Process.rlimit().

Availability: Linux, FreeBSD

Added in version 8.0.0.

class psutil.ConnectionStatus[source]

enum.StrEnum collection of CONN_* constants. Returned in the status field of psutil.net_connections() and Process.net_connections().

Added in version 8.0.0.

class psutil.NicDuplex[source]

enum.IntEnum collection of NIC_DUPLEX_* constants. Returned in the duplex field of psutil.net_if_stats().

Added in version 3.0.0.

class psutil.BatteryTime[source]

enum.IntEnum collection of POWER_TIME_* constants. May appear in the secsleft field of psutil.sensors_battery().

Added in version 5.1.0.

Operating system constants

bool constants which define what platform you’re on. True if on the platform, False otherwise.

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

Alias for MACOS.

Deprecated since version 5.4.7: use MACOS instead.

Process status constants

Represent the current status of a process. Returned by Process.status().

Changed in version 8.0.0: constants are now ProcessStatus enum members (were plain strings). See migration guide.

psutil.STATUS_RUNNING

The process is running or ready to run (e.g. while True: pass).

psutil.STATUS_SLEEPING

The process is dormant (e.g. during time.sleep()) but can be woken up, e.g. via a signal.

psutil.STATUS_DISK_SLEEP

The process is waiting for disk I/O to complete. The kernel usually ignores signals in this state to prevent data corruption. E.g. os.read(fd, 1024) on a slow / blocked device can produce this state.

psutil.STATUS_STOPPED

The process is stopped (e.g., by SIGSTOP or SIGTSTP, which is sent on Ctrl+Z) and will not run until resumed (e.g., via SIGCONT).

psutil.STATUS_TRACING_STOP

The process is temporarily halted because it is being inspected by a debugger (e.g. via strace -p <pid>).

psutil.STATUS_ZOMBIE

The process has finished execution and released its resources, but it remains in the process table until the parent reaps it via wait(). See also What is a zombie process?.

psutil.STATUS_DEAD

The process is about to disappear (final state before it is gone).

psutil.STATUS_WAKE_KILL

(Linux only) A variant of STATUS_DISK_SLEEP where the process can be awakened by SIGKILL. Used for tasks which might otherwise remain blocked indefinitely, e.g. unresponsive network filesystems such as NFS, as in open("/mnt/nfs_hung/file").read().

psutil.STATUS_WAKING

(Linux only) A transient state right before the process becomes runnable (STATUS_RUNNING).

psutil.STATUS_PARKED

(Linux only) A dormant state for kernel threads tied to a specific CPU. These threads are “parked” when a CPU core is taken offline and will remain inactive until the core is re-enabled.

Added in version 5.4.7.

psutil.STATUS_IDLE

(Linux, macOS, FreeBSD) A sleep for kernel threads waiting for work.

Added in version 3.4.1.

psutil.STATUS_LOCKED

(FreeBSD only) The process is blocked specifically waiting for a kernel-level synchronization primitive (e.g. a mutex).

Added in version 3.4.1.

psutil.STATUS_WAITING

(FreeBSD only) The process is waiting in a kernel sleep queue for a specific system event to occur.

Added in version 3.4.1.

psutil.STATUS_SUSPENDED

(NetBSD only) The process has been explicitly paused, similar to the stopped state but managed by the NetBSD scheduler.

Added in version 3.4.1.

Process priority constants

Represent the priority of a process on Windows (see SetPriorityClass doc). They can be used in conjunction with Process.nice() to get or set process priority.

Availability: Windows

Changed in version 8.0.0: constants are now ProcessPriority enum members (were plain integers). See migration guide.

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

Process I/O priority constants

Represent the I/O priority class of a process (Linux and Windows only). They can be used in conjunction with Process.ionice() (ioclass argument).

Linux (see ioprio_get(2)):

psutil.IOPRIO_CLASS_RT

Highest priority.

psutil.IOPRIO_CLASS_BE

Normal priority.

psutil.IOPRIO_CLASS_IDLE

Lowest priority.

psutil.IOPRIO_CLASS_NONE

No priority set (default; treated as IOPRIO_CLASS_BE).

Windows:

psutil.IOPRIO_VERYLOW
psutil.IOPRIO_LOW
psutil.IOPRIO_NORMAL
psutil.IOPRIO_HIGH

Added in version 5.6.2.

Changed in version 8.0.0: constants are now ProcessIOPriority enum members. See migration guide.

Process resource constants

Constants for getting or setting process resource limits, to be used in in conjunction with Process.rlimit(). The meaning of each constant is explained in resource.getrlimit() documentation.

Availability: Linux, FreeBSD

Changed in version 8.0.0: these constants are now ProcessRlimit enum members (were plain integers). See migration guide.

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

Added in version 5.7.3.

psutil.RLIMIT_SBSIZE

Added in version 5.7.3.

psutil.RLIMIT_NPTS

Added in version 5.7.3.

Connections constants

enum.StrEnum constants representing the status of a TCP connection. Returned by Process.net_connections() and psutil.net_connections() (status field).

Changed in version 8.0.0: constants are now ConnectionStatus enum members (were plain strings). See migration guide.

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)

Hardware constants

psutil.NIC_DUPLEX_FULL
psutil.NIC_DUPLEX_HALF
psutil.NIC_DUPLEX_UNKNOWN

Identifies whether a NIC operates in full, half, or unknown duplex mode. FULL allows simultaneous send/receive, HALF allows only one at a time. Returned by psutil.net_if_stats() (duplex field).

Added in version 3.0.0.

psutil.POWER_TIME_UNKNOWN
psutil.POWER_TIME_UNLIMITED

Whether the remaining time of a battery cannot be determined or is unlimited. May be assigned to psutil.sensors_battery()’s secsleft field.

Added in version 5.1.0.

Other 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 /proc is mounted elsewhere, or if you want to retrieve 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-related APIs and many (but not all) Process class methods).

Availability: Linux, SunOS, AIX

Added 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.version_info

A tuple to check psutil installed version.

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

Environment variables

PSUTIL_DEBUG

If set, psutil will print debug messages to stderr. This is useful for troubleshooting internal errors or understanding the library’s behavior at a lower level. The variable is checked at import time, and affects both the Python layer and the underlying C extension modules. It can also be toggled programmatically at runtime via psutil._set_debug(True).

$ PSUTIL_DEBUG=1 python3 script.py

Added in version 5.4.2.