Welcome to pypsutil’s documentation!

About

pypsutil is a partial reimplementation of the popular psutil. It is written in pure Python (when necessary, it calls library functions using ctypes).

pypsutil vs. psutil

Reasons to use pypsutil instead of psutil:

  • You do not want dependencies that require C extensions (for whatever reason)
  • You need some of the extra features that pypsutil provides (such as Process.getgroups() and the increased availability of Process.rlimit())
  • You are using a type checker in your project (all of pypsutil’s public interfaces have type annotations, unlike psutil)

Reasons not to use pypsutil instead of psutil:

  • You need to support Windows, Solaris, and/or AIX (pypsutil currently does not support these platforms)
  • You need to support Python versions prior to 3.7 (pypsutil is Python 3.7+ only)
  • You are concerned about speed (no benchmarks have been conducted, but psutil is likely faster because it is partially written in C)
  • You need professional support
  • You need some of the features of psutil that pypsutil does not provide (check this documentation to see if the features you need are present)
  • You want a drop-in replacement for psutil (see the note below)

pypsutil aims to implement many of the features of psutil; however, support is currently incomplete.

Important

pypsutil does NOT slavishly follow psutil’s API. Specifically:

  • When possible, pypsutil avoids having a single function perform multiple different operations (mainly get vs. set) depending on the arguments it is passed. (Besides being better from a design perspective, this simplifies type annotations.)

    For example, Process.nice() (from psutil) is split into two methods in pypsutil: Process.getpriority() and Process.setpriority(). Similarly, psutil’s cpu_times(percpu=True|False) is split into two functions: cpu_times() and percpu_times().

  • If an interface has been added to the standard library that (at least partially) overlaps with an interface from psutil, pypsutil may either a) remove the interface entirely or b) remove the portion that overlaps with the standard library, possibly renaming it in the process.

    For example, os.cpu_count() was added in Python 3.4, and it retrieves the same information as psutil.cpu_count(logical=True). As a result, pypsutil does not offer a cpu_count() function; instead, it offers a physical_cpu_count() function that covers the case of psutil.cpu_count(logical=False).

Platform Support

Currently, the following platforms are supported:

  • Linux
  • macOS
  • FreeBSD
  • OpenBSD
  • NetBSD

Not all platforms support all interfaces. Availability of different functions on different platforms is noted in the documentation.

Process information

class Process(pid=None)

Represents the process with the specified pid. (If pid is None, the PID of the current process is used.)

This class will retrieve the process’s creation time and use the combination of PID + creation time to uniquely identify the process, helping to prevent bugs if the process exits and the PID is reused by the operating system.

pid

The process’s PID. This attribute is read-only.

Type:int
ppid()

Returns the parent process’s PID.

Returns:The PID of this process’s parent process
Return type:int
parent()

Returns a a Process object representing this process’s parent process, or None if the parent process cannot be determined.

Note: This method preemptively checks if this process’s PID has been reused.

Returns:a Process object representing this process’s parent process, or None if the parent process cannot be determined
Return type:Process or None
parents()

Returns a list of this process’s parents. This is a helper that is effectively equivalent to calling parent() repeatedly until it returns None.

Note: This method preemptively checks if this process’s PID has been reused.

Returns:a list of Process objects representing this process’s parents
Return type:list[Process]
children(*, recursive=False)

Get a list of the children of this process. If recursive is True, includes all descendants.

Parameters:recursive (bool) – If True, include all descendants of this process’s children
Returns:a list of Process objects representing this process’s children
Return type:list[Process]
create_time()

Get the creation time of this process.

Returns:The creation time of this process, in seconds since the Unix epoch
Return type:float
pgid()

Get the processs group ID of this process.

Returns:The process group ID of this process
Return type:int
sid()

Get the session ID of this process.

Returns:The session ID of this process
Return type:int
status()

Get the current process status as one of the members of the ProcessStatus enum.

Returns:The current process status
Return type:ProcessStatus
name()

Get the name of this process.

Returns:The name of this process
Return type:str
exe(*, fallback_cmdline=True)

Get the path to this process’s executable.

On some platforms (such as OpenBSD) this cannot be obtained directly. On those platforms, if fallback_cmdline is True, this method will return the first command-line argument (if it is not an absolute path, a lookup will be performed on the system PATH).

If the path to the process’s executable cannot be determined (for example, if the PATH lookup fails on OpenBSD), this function will return an empty string.

Parameters:bool (fallback_cmdline) – Whether to fall back on checking the first command-line argument if the OS does not provide a way to get the executable path. (This is much less reliable.)
Returns:The path to this process’s executable
Return type:str
cmdline()

A list of strings representing this process’s command line.

Returns:This process’s command line as a list of strings
Return type:list[str]
cwd()

Get this process’s current working directory.

Returns:This process’s current working directory
Return type:str
root()

Get this process’s root directory.

Returns:This process’s root directory
Return type:str

Availability: Linux

environ()

Return this process’s environmenal variables as a dictionary of strings.

Note: This may not reflect changes since the process was started.

Returns:This process’s environment as a dict
Return type:dict[str, str]
uids()

Get the real, effective, and saved UIDs of this process

Returns:A tuple containing the UIDs of this process
Return type:tuple[int, int, int]
gids()

Get the real, effective, and saved GIDs of this process

Returns:A tuple containing the GIDs of this process.
Return type:tuple[int, int, int]
getgroups()

Get the supplementary group list of this process.

Note

Currently, on Windows Subsystem for Linux 1 (not on WSL 2), this function succeeds but always returns an empty list.

Note

On macOS, this function’s behavior differs from that of os.getgroups(). Effectively, it always behaves as if the deployment target is less than 10.5.

Returns:A list of this process’s supplementary group IDs.
Return type:list[int]
username()

Get the username of the user this process is running as.

Currently, this just takes the real UID and uses pwd.getpwuid() to look up the username. If that fails, it converts the real UID to a string and returns that.

Returns:The username of the user this process is running as
Return type:str
umask()

Get the umask of this process.

Returns None if it is not possible to get the umask on the current version of the operating system.

Note: On FreeBSD, this will raise AccessDenied for PID 0.

Availability: Linux (4.7+), FreeBSD

Returns:The umask of this process
Return type:int or None
sigmasks(*, include_internal=False)

Get the signal masks of this process.

This returns a dataclass with several attributes:

  • pending (not on macOS): The signals that are pending for this process.
  • blocked (not on macOS): The signals that are blocked for this process (i.e. the signal mask set with pthread_sigmask()).
  • ignored: The signals that are ignored by this process (i.e. SIG_IGN).
  • caught: The signals for which this process has registered signal handlers.
  • process_pending (Linux-only): The signals that are pending for the process as a whole, not just this thread.

All of these are set objects.

Note

Currently, on Windows Subsystem for Linux 1 (not on WSL 2), this function succeeds but always returns empty sets for all fields.

Parameters:include_internal (bool) – If this is True, then implementation-internal signals may be included – for example, on Linux this affects the two or three signals used by the glibc/musl POSIX threads implementations.
Returns:The signal masks of this process.
Return type:ProcessSignalMasks
cpu_times()

Get the accumulated process times.

This returns a dataclass with several attributes:

  • user: Time spent in user mode
  • system: Time spent in kernel mode
  • children_user: Time spent in user mode by child processes (0 on macOS)
  • children_system: Time spent in kernel mode (0 on macOS)

Note: On OpenBSD and NetBSD, children_user and children_system are both set to the combined user + system time.

Returns:The accumulated process times
Return type:ProcessSignalMasks
rlimit(res, new_limits=None)

Get/set the soft/hard resource limits of the process. Equivalent to resource.prlimit(proc.pid, res, new_limits), but may be implemented on more platforms.

Warning

On some platforms, this method may not be able to get/set the limits atomically, or to set the soft and hard resource limits together.

Aside from the potential race conditions this creates, if this method raises an error, one or both of the limits may have been changed before the error occurred. In this case, no attempts are made to revert the changes.

Parameters:
  • res (int) – The number of the resource to set (one of the resource.RLIMIT_* constants)
  • new_limits (tuple[int, int] or None) – The new (soft, hard) limits to set (or None to only get the old resource limits). Use resource.RLIM_INFINITY for infinite limits.
Returns:

A tuple of the old (soft, hard) resource limits

Return type:

tuple[int, int]

Availability: Linux, FreeBSD, NetBSD

getrlimit(res)

Get the current soft/hard resource limits of the process. Equivalent to resource.prlimit(proc.pid, res, None), but may be implemented on more platforms.

Currently, the availability of this method is the same as for rlimit(). However, that may change if pypsutil adds supports for platforms that allow for getting, but not setting, resource limits for other processes.

Note

As with rlimit(), this method may not be able to get the soft and hard resource limits together. As a result, there is a race condition: If the process’s resource limits are changed while this method is reading them, this method may return a combination such as (old soft, new hard) or (new soft, old hard) (where “old” means the values before the change and “new” means the values after the change).

Parameters:res (int) – The number of the resource to set (one of the resource.RLIMIT_* constants)
Returns:A tuple of the current (soft, hard) resource limits
Return type:tuple[int, int]

Availability: Linux, FreeBSD, NetBSD

terminal()

Get the name of this process’s controlling terminal. Returns None if the process has no controlling terminal, or if its name cannot be found.

Note

In most cases, the name returned by this function will be the same as with the tty command or os.ttyname(0). However, this function returns the name of the process’s controlling terminal; tty and os.ttyname(0) return the name of the terminal connected to standard input (if the process’s standard input is a terminal).

In most cases, these will be the same thing. However, they are not technically required to be, and in some edge cases they may be different.

Returns:The name of this process’s controlling terminal
Return type:str or None
getpriority()

Equivalent to os.getpriority(os.PRIO_PROCESS, proc.pid) in most cases. (However, on systems where the kernel appears as PID 0, Process(0).getpriority() will actually operate on PID 0.)

Returns:The process’s scheduling priority (a.k.a. nice value)
Return type:int
setpriority(prio)

Equivalent to os.setpriority(os.PRIO_PROCESS, proc.pid, prio), but preemptively checks for PID reuse.

(Note: on systems where the kernel appears as PID 0, attempting to set the priority of PID 0 will always fail with an AccessDenied exception.)

Parameters:prio (int) – The new scheduling priority (a.k.a. nice value) for the process
send_signal(sig)

Send the specified signal to this process, preemptively checking for PID reuse.

Other than the PID reuse check, this is equivalent to os.kill(proc.pid, sig).

Parameters:sig (int) – The signal number (one of the signal.SIG* constants)
suspend()

Suspends process execution, preemptively checking for PID reuse. Equivalent to proc.send_signal(signal.SIGSTOP).

resume()

Resumes process execution, preemptively checking for PID reuse. Equivalent to proc.send_signal(signal.SIGSCONT).

terminate()

Terminates the process, preemptively checking for PID reuse. Equivalent to proc.send_signal(signal.SIGTERM).

kill()

Kills the process, preemptively checking for PID reuse. Equivalent to proc.send_signal(signal.SIGKELL).

is_running()

Checks if the process is still running. Unlike pid_exists(proc.pid), this also checks for PID reuse.

Note: The following methods preemptively check whether the process is still running and raise NoSuchProcess if it has exited:

Returns:Whether the process is still running
Return type:int
wait(*, timeout=None)

Wait for the process to exit. If this process was a child of the current process, its exit code is returned.

Raises TimeoutExpired if the timeout expires.

Parameters:timeout (int or float or None) – The maximum amount of time to wait for the process to exit (None signifies no limit).
Raises:TimeoutExpired – If the timeout expires
Returns:The exit code of the process if it can be determined; otherwise None
Return type:int or None
oneshot()

This is a context manager which enables caching pieces of information that can be obtained via the same method.

Here is a table, in the same format as psutil.Process.oneshot()’s table, that shows which methods can be grouped together for greater efficiency:

Linux macOS FreeBSD/OpenBSD/NetBSD
name() name() name()
status() status() status()
ppid() ppid() ppid()
terminal() [2] pgid() [1] pgid() [1]
cpu_times() uids() sid() [1]
  gids() uids()
uids() username() gids()
gids() getgroups() username()
username() terminal() [2] getgroups() [3]
getgroups() sigmasks() terminal() [2]
umask() cpu_times() sigmasks()
sigmasks()   cpu_times()
  cmdline()  
  environ()  
[1](1, 2, 3) These functions, when called inside a oneshot() context manager, will retrieve the requested information in a different way that collects as much extra information as possible about the process for later use.
[2](1, 2, 3) Because of implementation details, terminal() will likely only see a minor speedup.
[3]On FreeBSD, calling getgroups() inside a oneshot() will first attempt to retrieve the group list via a method that collects as much extra information as possible. However, this method may truncate the returned group list. In this case, getgroups() will fall back on the normal method, which avoids truncation.
class ProcessStatus

An enum representing a process’s status.

RUNNING
SLEEPING
DISK_SLEEP
ZOMBIE
STOPPED
TRACING_STOP
DEAD
WAKE_KILL
WAKING
PARKED
IDLE
LOCKED
WAITING
pids()

Get a list of the PIDs of running processes.

Returns:A list of the PIDs of running processes.
Return type:list[int]
process_iter()

Return an iterator over the running processes.

Note: On Linux, if /proc is mounted with hidepid=1, it is not possible to get the process creation time (or indeed, any information except the PID/UID/GID of the process) of other users’ processes when running an unprivileged user. This function will raise a AccessDenied if that occurs; if you wish to simply skip these processes then use process_iter_available() instead.

Return type:iterator[Process]
process_iter_available()

Return an iterator over the running processes, except that a process will be skipped if a permission error is encountered while trying to retrieve its creation time. (This can happen, for example, on Linux if /proc is mounted with hidepid=1.)

Return type:iterator[Process]
pid_exists(pid)

Checks whether a process with the given PID exists. This function will use the most efficient method possible to perform this check.

Note: Use Process.is_running() if you want to check whether a Process has exited.

Parameters:pid (int) – The PID to check for existence
Returns:Whether the process with the given PID exists
Return type:bool
wait_procs(procs, timeout=None, callback=None)

Wait for several Process instances to terminate, and returns (gone, alive) tuple indicating which have terminated and which are still alive.

If the timeout expires, this function will not raise TimeoutExpired.

Parameters:
  • procs (iterable[int]) – The processes that should be waited for
  • timeout (int or float or None) – The maximum amount of time to wait for the processes to terminate
  • callback – A function which will be called with the Process as an argument when one of the processes exits.
Return type:

tuple[list[Process], list[Process]]

System information

boot_time()

Get the system boot time as a number of seconds since the Unix epoch.

Returns:The system boot time as a number of seconds since the Unix epoch
Return type:float
time_since_boot()

Get the number of seconds elapsed since the system booted.

Usually, this is approximately the same as time.time() - pypsutil.boot_time(). However, it may be more efficient. (On some systems, boot_time() may just return time.time() - pypsutil.time_since_boot()!)

Returns:The number of seconds elapsed since the system booted
Return type:float
uptime()

Get the system uptime. This is similar to time_since_boot(), but it does not count time the system was suspended.

Returns:The system uptime
Return type:float

Availability: Linux, macOS, FreeBSD, OpenBSD

virtual_memory()

Return a dataclass containing system memory statistics. Currently, the following fields are available:

  • total: Total physical memory in bytes
  • available: Amount of memory that can be made available without using swap (or killing programs)
  • used: Used memory in bytes
  • free: Free memory (immediately available) in bytes
  • active: Memory currently in use or recently used (unlikely to be reclaimed)
  • inactive: Memory not recently used (more likely to be reclaimed)
  • buffers: Temporary disk storage
  • cached: Disk cache
  • shared: Memory used for shared objects (tmpfs-es on Linux)
  • slab: In-kernel data structure cache

The dataclass also has a percent property that returns the usage percentage (0-100).

In most cases, you should only use total, available and percent.

Returns:A dataclass containing system memory statistics
Return type:VirtualMemoryInfo

Availability: Linux

swap_memory()

Return a dataclass containing system swap memory statistics. Currently, the following fields are available:

  • total: Total swap memory in bytes
  • used: Used swap memory in bytes
  • free: Free swap memory in bytes
  • sin: Cumulative number of bytes the system has swapped in from the disk
  • sout: Cumulative number of bytes the system has swapped out from the disk

The dataclass also has a percent property that returns the usage percentage (0-100).

Returns:A dataclass containing system swap memory statistics
Return type:SwapInfo

Availability: Linux

disk_usage(path)

Return disk usage statistics about the filesystem which contains the given path.

Current attributes:

  • total: Total disk space in bytes
  • used: Total used disk space in bytes
  • free: Disk space in bytes that is free and available for use by unprivileged users
  • percent: Percentage of disk space used (out of the space available to unprivileged users)
Returns:A dataclass containing disk usage statistics about the filesystem which contains the given path
Return type:DiskUsage
physical_cpu_count()

Get the number of physical CPUs in the system (i.e. excluding Hyper Threading cores) or``None`` if that cannot be determined.

Currently, this always returns None on OpenBSD and NetBSD.

Returns:The number of physical CPUs in the system (or None if unable to determine)
Return type:int or None
cpu_freq()

Returns an instance of a dataclass with current, min`, and ``max attributes, representing the current, minimum, and maximum CPU frequencies.

Returns:An instance of a dataclass containing the current, minimum, and maximum CPU frequencies.
Return type:CPUFrequencies

Availability: Linux

percpu_freq()

Identical to cpu_freq(), but returns a list representing the frequency for each CPU.

Returns:A list of the frequencies of each CPU.
Return type:CPUFrequencies

Availability: Linux

cpu_times()

Returns a dataclass containing information about system CPU times. Each attribute represents the time in seconds that the CPU has spent in the corresponding mode (since boot):

  • user: Time spent in user mode (includes guest time on Linux)
  • system: Time spent in kernel mode
  • idle: Time spent doing nothing

Extra platform-specific fields:

  • nice (Linux/BSDs/macOS): Time spent by prioritized processes in user mode (includes guest_nice time on Linux)
  • iowait (Linux): Time spent waiting for I/O to complete
  • irq (Linux/BSDs): Time spent servicing hardware interrupts
  • softirq (Linux): Time spent servicing software interrupts
  • lock_spin (OpenBSD): Time spent “spinning” on a lock
  • steal (Linux): Time spent running other operating systems in a virtualize environment
  • guest (Linux): Time spent running a virtual CPU for a guest operating system
  • guest_nice (Linux): Time spent running a niced guest
Returns:A dataclass containing information about system CPU times.
Return type:CPUTimes

Availability: Linux, FreeBSD, OpenBSD, NetBSD

percpu_times()

Identical to cpu_times(), but returns a list representing the times for each CPU.

Returns:A list of the times of each CPU.
Return type:CPUTimes

Availability: Linux, FreeBSD, OpenBSD, NetBSD

cpu_stats()

Return a dataclass containing various statistics:

  • ctx_switches: The number of context switches since boot.
  • interrupts: The number of interrupts since boot.
  • soft_interrupts: The number of software interrupts since boot.
  • syscalls: The number of system calls since boot (always 0 on Linux)
Returns:A dataclass containing some CPU statistics.
Return type:CPUStats

Availablity: Linux

Exceptions

class Error

Base exception class

class NoSuchProcess(pid)

Raised by methods of Process when no process with the given PID is found.

class ZombieProcess(pid)

Raised by methods of Process if 1) the process has become a zombie process and 2) it is not possible to retrieve the requested information for zombie processes.

This is a subclass of NoSuchProcess.

class AccessDenied(pid)

Raised by methods of Process when permission to perform an action is denied.

class TimeoutExpired(seconds, pid=None)

Raised if a timeout expires.

Indices and tables