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
Processinstance for all running processes. This should be preferred overpsutil.pids()to iterate over processes, as retrieving info is safe from race conditions.Every
Processinstance is only created once, and then cached for the next timepsutil.process_iter()is called (if PID is still alive). Cache can optionally be cleared viaprocess_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. SeeProcess.attrsfor a list of valid attrs names.If a method raises
AccessDeniedduring pre-fetch, it will return ad_value (defaultNone) 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
Processinstances are reused across calls, a subsequentprocess_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
Processinstance, so that subsequent method calls (e.g.p.name(),p.status()) return the cached values instead of making new system calls. TheProcess.infodict is deprecated in favor of this new approach.Passing an empty list (
attrs=[]) to mean “all attributes” is deprecated; useProcess.attrsinstead.
- 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
Processinstances to terminate. Return a(gone, alive)tuple. Thegoneprocesses will have a newreturncodeattribute set byProcess.wait().callback is called with a
Processinstance whenever a process terminates.Returns as soon as all processes terminate or timeout (seconds) expires. Unlike
Process.wait(), it does not raiseTimeoutExpiredon 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
Processclass 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 ifProcess.name()was called before the process disappeared.See also
- exception psutil.ZombieProcess(pid, name=None, ppid=None, msg=None)
Subclass of
NoSuchProcess. Raised byProcessmethods when encountering a zombie process on UNIX (Windows does not have zombies). name and ppid attributes are set ifProcess.name()orProcess.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.See also
Added in version 3.0.0.
- exception psutil.AccessDenied(pid=None, name=None, msg=None)
Raised by
Processmethods when an action is denied due to insufficient privileges. name is set ifProcess.name()was called before the exception was raised.See also
- 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 ifProcess.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. RaisesNoSuchProcessif pid does not exist.On Linux, pid can also refer to a thread ID (the
idfield returned bythreads()).When calling methods of this class, always be prepared to catch
NoSuchProcessandAccessDeniedexceptions. The builtinhash()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 aset.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 raiseNoSuchProcessif the PID has been reused. See PID reuse for details.Note
To fetch multiple attributes efficiently, use the
oneshot()context manager or theas_dict()utility method.- pid
The process PID as a read-only property.
- attrs
A
frozensetof strings representing the valid attribute names accepted byas_dict()andprocess_iter(). It defaults to all read-onlyProcessmethod names, minus the utility methods such asas_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 withattrsargument. Accessing this attribute is deprecated and raisesDeprecationWarning. Use method calls instead (e.g.p.name()instead ofp.info['name']) orprocess_iter()+Process.as_dict()if you need a dict structure.See also
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 ... >>>
See also
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
Processclass’s attribute names. If not passed allProcess.attrsnames are assumed.ad_value is the value which gets assigned to a dict key in case
AccessDeniedorZombieProcessexception is raised when retrieving that particular process information (defaultNone).The
'net_connections'attribute is retrieved by callingProcess.net_connections()withkind="inet".Internally,
as_dict()usesoneshot()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
ZombieProcessexception, not onlyAccessDenied.
- 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()andparents()methods.
- parent()[source]
Utility method which returns the parent process as a
Processobject, preemptively checking whether PID has been reused. If no parent PID is known returnNone. See alsoppid()andparents()methods.
- parents()[source]
Utility method which returns the parents of this process as a list of
Processinstances. If no parents are known return an empty list. See alsoppid()andparent()methods.Added in version 5.6.0.
- status()[source]
The current process status as a
ProcessStatusenum member. The returned value is one of theSTATUS_*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
ProcessStatusenum member instead of a plainstr. 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
realprocess UID fromuids().
- uids()[source]
The
real,effectiveandsaveduser ID of this process as a named tuple. This is the same asos.getresuid(), but can be used for any process PID.Availability: UNIX
- gids()[source]
The
real,effectiveandsavedgroup ID of this process as a named tuple. This is the same asos.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 tottycommand 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
-20to20. 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:
This method was later incorporated in Python 3.3 as
os.getpriority()andos.setpriority()(see BPO-10784).Changed in version 8.0.0: on Windows, the return value is now a
ProcessPriorityenum 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 from0to7can 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
ProcessIOPriorityenum 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 stdlibresource.getrlimit()andresource.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)
See also
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 (-1on BSD).write_bytes: bytes written (-1on BSD).
Linux specific:
read_chars(Linux): bytes read viaread()andpread()syscalls. Unlikeread_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 viawrite()andpwrite()syscalls. Same caveats asread_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_charsandwrite_charsfields.Changed in version 5.2.0: Windows: added
other_countandother_bytesfields.
- num_ctx_switches()[source]
The number of context switches performed by this process as a
(voluntary, involuntary)named tuple (cumulative counter).Note
(Windows, macOS)
involuntaryvalue is always set to 0, whilevoluntaryvalue 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
- 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. Ifpidrefers to the current process, this matchesthreading.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 (always0on Windows and macOS).children_system: system time of all child processes (always0on Windows and macOS).iowait: (Linux) time spent waiting for blocking I/O to complete. (iowait). Excluded fromuserandsystemtimes 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_userandchildren_systemfields.Changed in version 5.6.4: Linux: added
iowaitfield.
- cpu_percent(interval=None)[source]
Return process CPU utilization as a percentage. Values can exceed
100.0if the process runs multiple threads on different CPUs.If interval is >
0.0, measures CPU times before and after the interval (blocking). If0.0orNone, returns the utilization since the last call or module import, returning immediately. That means the first time this is called it will return a meaningless0.0value which you are supposed to ignore. In this case it is recommended for accuracy that this method be called with at least0.1seconds 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 Windowstaskmgr.exebehavior: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 withpsutil.cpu_percent(percpu=True)to observe the system workload distributed across multiple CPUs.See also
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
rssandvms.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 thetopRES column. On Windows maps toWorkingSetSize.vms: aka VMS. On UNIX matches thetopVIRT column. On Windows maps toPrivateUsage(private committed pages only), which differs from the UNIX definition; usevirtualfrommemory_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. Matchestop’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. Matchestop’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 (seestack). Matchestop’s DATA column.stack(BSD): size of the process stack segment. Reported separately fromdata(unlike Linux where both are combined).peak_rss(BSD, Windows): see peak_rss. On BSD may be0for kernel PIDs. On Windows maps toPeakWorkingSetSize.peak_vms(Windows): see peak_vms. Maps toPeakPagefileUsage.
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)
See also
Changed in version 4.0.0: multiple fields are returned, not only
rssandvms.Changed in version 8.0.0: (see migration guide)
Linux:
libanddirtyremoved (always 0 since Linux 2.6). Deprecated aliases returning 0 and emittingDeprecationWarningare kept.macOS: removed
pfaultsandpageinsfields with no backward-compatible aliases. Usepage_faults()instead.Windows: eliminated old aliases:
wset→rss,peak_wset→peak_rss,pagefileandprivate→vms,peak_pagefile→peak_vms,num_page_faults→page_faults()method. At the same timepaged_pool,nonpaged_pool,peak_paged_pool,peak_nonpaged_poolwere moved tomemory_info_ex(). All these old names still work but raiseDeprecationWarning.BSD: added
peak_rssfield.
- 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 asmemory_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_shmemequalsrss. 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 tomemory_footprint().swapbut cheaper, as it reads from/proc/pid/statusinstead of/proc/pid/smaps.compressed(macOS): memory held in the in-RAM memory compressor; not counted inrss. 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 andfootprint(1)report; prefer this overrssmacOS memory monitoring.virtual(Windows): true virtual address space size, including reserved-but-uncommitted regions (unlikevmsinmemory_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,pssandswapmemory metrics. These give a more accurate picture of actual memory consumption thanmemory_info(). It walks the full process address space, so it is slower thanmemory_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)
See also
Availability: Linux, macOS, Windows
Added in version 8.0.0.
- memory_full_info()[source]
This deprecated method returns the same information as
memory_info()plusmemory_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(), ormemory_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 isFalse, 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 exceedrssif parts have never been accessed.pss: PSS for this mapping, that isrsssplit 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
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
Processinstances. If recursive isTrue, 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 toopen()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 underlyingos.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
Windows: this is not guaranteed to enumerate all file handles (see Why does open_files() not return all files on Windows?)
BSD: can return empty-string paths due to a kernel bug (see issue 595)
Changed in version 3.1.0: no longer hangs on Windows.
Changed in version 4.1.0: Linux: added
position,modeandflagsfields.
- net_connections(kind='inet')[source]
Same as
psutil.net_connections()but for this process only (the returned named tuples have nopidfield). 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
Truealso 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
signalmodule constants), preemptively checking whether PID has been reused. On UNIX this is the same asos.kill(pid, sig). On Windows onlySIGTERM,CTRL_C_EVENTandCTRL_BREAK_EVENTsignals are supported, andSIGTERMis treated as an alias forkill().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
SIGSTOPsignal, preemptively checking whether PID has been reused. On UNIX this is the same asos.kill(pid, signal.SIGSTOP). On Windows this is done by suspending all process threads.
- resume()[source]
Resume process execution with
SIGCONTsignal, preemptively checking whether PID has been reused. On UNIX this is the same asos.kill(pid, signal.SIGCONT). On Windows this is done by resuming all process threads.
- terminate()[source]
Terminate the process with
SIGTERMsignal, preemptively checking whether PID has been reused. On UNIX this is the same asos.kill(pid, signal.SIGTERM). On Windows this is an alias forkill().See also
how to kill a process tree.
- kill()[source]
Kill the current process by using
SIGKILLsignal, preemptively checking whether PID has been reused. On UNIX this is the same asos.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 ofos.getpid()(current process), it just waits until the process disappears and returnNone. If PID does not exist returnNoneimmediately.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=0can be used in non-blocking apps: it will either return immediately or raiseTimeoutExpired.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
Noneand the platform supports it, an efficient event-driven mechanism is used to wait for process termination:Linux >= 5.3 with Python >= 3.9 uses
os.pidfd_open()+select.poll()macOS and other BSD variants use
select.kqueue()+KQ_FILTER_PROC+KQ_NOTE_EXITWindows uses WaitForSingleObject
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
subprocessmodule 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()andselect.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 allpsutil.Processmethods 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
uordblksandhblkhdfields from glibc mallinfo2(3).heap_used: total number of bytes currently allocated viamalloc()(small allocations).mmap_used: total number of bytes currently allocated via mmap(2) or via largemalloc()allocations. Always set to 0 on macOS.heap_count: (Windows only) number of private heaps created viaHeapCreate().
>>> 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 withoutfree()heap_usedUNIX / glibc
large
malloc()>128KB withoutfree(), ormmap()withoutmunmap()mmap_usedWindows
HeapAlloc()withoutHeapFree()heap_usedWindows
VirtualAlloc()withoutVirtualFree()mmap_usedWindows
HeapCreate()withoutHeapDestroy()heap_countAvailability: 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 inheap_usedcome 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
WindowsServiceinstances 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
WindowsServiceinstance. RaiseNoSuchProcessif 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()andwin_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 newWindowsServiceinstance.
- 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 toProcessclass 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.StrEnumcollection ofSTATUS_*constants. Returned byProcess.status().Added in version 8.0.0.
- class psutil.ProcessPriority
enum.IntEnumcollection of*_PRIORITY_CLASSconstants forProcess.nice()on Windows.Availability: Windows
Added in version 8.0.0.
- class psutil.ProcessIOPriority[source]
enum.IntEnumcollection of I/O priority constants forProcess.ionice().IOPRIO_CLASS_*on Linux,IOPRIO_*on Windows.Availability: Linux, Windows
Added in version 8.0.0.
- class psutil.ProcessRlimit
enum.IntEnumcollection ofRLIMIT_*constants forProcess.rlimit().Availability: Linux, FreeBSD
Added in version 8.0.0.
- class psutil.ConnectionStatus[source]
enum.StrEnumcollection ofCONN_*constants. Returned in thestatusfield ofpsutil.net_connections()andProcess.net_connections().Added in version 8.0.0.
- class psutil.NicDuplex[source]
enum.IntEnumcollection ofNIC_DUPLEX_*constants. Returned in the duplex field ofpsutil.net_if_stats().Added in version 3.0.0.
- class psutil.BatteryTime[source]
enum.IntEnumcollection ofPOWER_TIME_*constants. May appear in the secsleft field ofpsutil.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
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
SIGSTOPorSIGTSTP, which is sent on Ctrl+Z) and will not run until resumed (e.g., viaSIGCONT).
- 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_SLEEPwhere the process can be awakened bySIGKILL. Used for tasks which might otherwise remain blocked indefinitely, e.g. unresponsive network filesystems such as NFS, as inopen("/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:
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:
Linux specific:
FreeBSD specific:
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.AF_LINK
Identifies a MAC address associated with a network interface. Returned by
psutil.net_if_addrs()(familyfield).Added in version 3.0.0.
- 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()(duplexfield).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()’ssecsleftfield.Added in version 5.1.0.
Other constants
- psutil.PROCFS_PATH
The path of the
/procfilesystem on Linux, Solaris and AIX (defaults to'/proc'). You may want to re-set this constant right after importing psutil in case/procis 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
/procfilesystem (e.g. memory-related APIs and many (but not all)Processclass 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.