ZetCode

Python psutil

last modified November 29, 2026 Python 3.15

In this article we show how to get information about the system and its processes with the psutil library.

psutil (process and system utilities) is a cross-platform library for retrieving information on CPU, memory, disks, network, sensors, and running processes. It implements many functions offered by command line tools such as ps, top, free, df, and uptime, and works on Linux, Windows, macOS, and the BSDs.

The examples were run on Linux with psutil 7.2. Most values describe the machine at the moment of the run, so the output will differ on every computer and in every run. We install the library from PyPI.

$ pip install psutil

CPU information

The cpu_count function returns the number of logical CPUs. With logical=False, it returns the number of physical cores.

cpu_info.py
import psutil

print(psutil.__version__)
print('logical CPUs:', psutil.cpu_count())
print('physical cores:', psutil.cpu_count(logical=False))

freq = psutil.cpu_freq()
print(f'frequency: {freq.current:.0f} MHz (max {freq.max:.0f} MHz)')

load1, load5, load15 = psutil.getloadavg()
print(f'load average: {load1:.2f} {load5:.2f} {load15:.2f}')

This machine has four cores with two hardware threads each. The cpu_freq function returns a named tuple with the current, minimum, and maximum frequency in MHz. The getloadavg function returns the average number of runnable processes over the last 1, 5, and 15 minutes.

$ python cpu_info.py
7.2.2
logical CPUs: 8
physical cores: 4
frequency: 3729 MHz (max 4200 MHz)
load average: 1.78 1.94 1.22

CPU usage

The cpu_percent function returns the CPU utilization as a percentage. With the interval argument, it measures the usage over that many seconds.

cpu_usage.py
import psutil

print(psutil.cpu_percent(interval=1))

per_cpu = psutil.cpu_percent(interval=1, percpu=True)
for i, pct in enumerate(per_cpu):
    bar = '#' * round(pct / 5)
    print(f'cpu{i:<2} {pct:5.1f}% {bar}')

times = psutil.cpu_times_percent(interval=1)
print(f'user {times.user}%  system {times.system}%  idle {times.idle}%')

With percpu=True, the function returns a list with one value per logical CPU, which we draw as a simple bar chart. The cpu_times_percent function splits the usage into user, system, idle, and other times. Each call with interval=1 blocks for one second, so the program runs for three seconds.

$ python cpu_usage.py
8.8
cpu0    8.1% ##
cpu1    9.1% ##
cpu2    9.0% ##
cpu3   11.0% ##
cpu4   11.2% ##
cpu5    8.1% ##
cpu6   23.2% #####
cpu7    9.2% ##
user 12.6%  system 2.0%  idle 85.1%

Memory

The virtual_memory function returns statistics about the physical memory, and swap_memory about the swap space. All sizes are in bytes.

memory.py
import psutil


def human(n):
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB']:
        if n < 1024:
            return f'{n:.1f} {unit}'
        n /= 1024
    return f'{n:.1f} PiB'


mem = psutil.virtual_memory()

print('total:    ', human(mem.total))
print('available:', human(mem.available))
print('used:     ', human(mem.used))
print(f'percent:   {mem.percent}%')

swap = psutil.swap_memory()
print('swap:     ', human(swap.used), 'of', human(swap.total))

The human function converts bytes to binary units. The available field is the memory that can be given to processes without swapping; it is the right value for checking whether the system is low on memory. It is larger than total - used, because the kernel can release caches.

$ python memory.py
total:     15.4 GiB
available: 6.1 GiB
used:      9.3 GiB
percent:   60.5%
swap:      2.0 GiB of 2.0 GiB

Disks

The disk_partitions function lists mounted partitions and disk_usage returns the total, used, and free space of a mount point.

disks.py
import psutil


def gib(n):
    return f'{n / 2**30:6.1f} GiB'


seen = set()

for part in psutil.disk_partitions():
    if part.fstype == 'squashfs' or part.device in seen:
        continue
    seen.add(part.device)
    usage = psutil.disk_usage(part.mountpoint)
    print(f'{part.device:16} {part.mountpoint:10} {part.fstype:5} '
          f'{gib(usage.total)} {usage.percent:5.1f}% used')

io = psutil.disk_io_counters()
print(f'read {io.read_bytes / 2**30:.1f} GiB, '
      f'written {io.write_bytes / 2**30:.1f} GiB since boot')

On Linux, the list also contains read-only squashfs images of snap packages, and a device can be mounted at several places. We skip both. The disk_io_counters function returns the number of bytes read and written since boot.

$ python disks.py
/dev/nvme0n1p2   /          ext4   456.9 GiB  88.3% used
/dev/nvme0n1p1   /boot/efi  vfat     0.5 GiB   1.2% used
read 15.7 GiB, written 16.3 GiB since boot

System and network

The boot_time function returns the time of the last boot as a Unix timestamp. The users, net_io_counters, and net_if_addrs functions describe the logged-in users and the network.

system.py
import time
from datetime import datetime

import psutil

boot = psutil.boot_time()
print('booted:', datetime.fromtimestamp(boot).isoformat(' ', 'seconds'))

uptime = int(time.time() - boot)
hours, rest = divmod(uptime, 3600)
print(f'uptime: {hours} h {rest // 60} min')

print('users logged in:', len(psutil.users()))

net = psutil.net_io_counters()
print(f'network: {net.bytes_recv / 2**20:.0f} MiB received, '
      f'{net.bytes_sent / 2**20:.0f} MiB sent')

print('interfaces:', sorted(psutil.net_if_addrs()))

We convert the boot time to a datetime and compute the uptime with divmod. The network counters are totals for all interfaces since boot. The net_if_addrs function returns a dictionary that maps interface names to their addresses; we print only the names.

$ python system.py
booted: 2026-11-29 08:54:13
uptime: 5 h 34 min
users logged in: 1
network: 2585 MiB received, 129 MiB sent
interfaces: ['br-c2f7cde7b7b3', 'docker0', 'lo', 'wlp0s20f3']

The current process

A Process object represents one process. Without an argument, it represents the current Python process.

current.py
import os

import psutil

p = psutil.Process()

print(p.pid == os.getpid())
print(p.name())
print(p.exe())
print(p.cmdline())
print(p.status())
print(p.username())
print(p.parent().name())

mem = p.memory_info()
print(f'rss {mem.rss / 2**20:.1f} MiB, vms {mem.vms / 2**20:.1f} MiB')

total = sum(i * i for i in range(3_000_000))
cpu = p.cpu_times()
print(f'user {cpu.user:.2f} s, system {cpu.system:.2f} s')
print(p.num_threads(), len(p.open_files()))

Each method reads a piece of information from the operating system: the name, the path of the executable, the command line, the status, and the owner. The exe method resolves symbolic links, so for a virtual environment it shows the real interpreter. The parent method returns the process that started the script, here the shell. The memory_info method returns the resident set size (rss), the physical memory used, and the virtual memory size (vms). We burn some CPU time before reading cpu_times.

$ python current.py
True
python
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/bin/python3.15
['python', 'current.py']
running
user
bash
rss 16.1 MiB, vms 47.9 MiB
user 0.15 s, system 0.00 s
1 0

Reading many attributes

Each method call may read files in /proc or make a system call. The oneshot context manager caches the data, so several calls are much faster. The as_dict method returns many attributes at once.

oneshot.py
import psutil

p = psutil.Process()

with p.oneshot():
    print(p.name(), p.ppid(), p.status())
    print(p.cpu_times().user >= 0, p.memory_percent() > 0)

info = p.as_dict(attrs=['pid', 'name', 'num_threads', 'nice'])
print(sorted(info))
print(info['name'], info['num_threads'], info['nice'])

Inside the with block, values that come from the same source are read only once. The as_dict method uses oneshot internally and returns a dictionary with the requested attributes.

$ python oneshot.py
python 50743 running
True True
['name', 'nice', 'num_threads', 'pid']
python 1 0

Listing processes

The process_iter function yields a Process object for each running process. With a list of attribute names, it fills the info dictionary of each process in one pass.

top_memory.py
import psutil

procs = []

for p in psutil.process_iter(['pid', 'name', 'memory_info']):
    mem = p.info['memory_info']
    if mem is None:
        continue
    procs.append((mem.rss, p.info['pid'], p.info['name']))

procs.sort(reverse=True)

print(f'{len(procs)} processes')
print(f'{"PID":>7}  {"RSS":>9}  NAME')

for rss, pid, name in procs[:5]:
    print(f'{pid:>7}  {rss / 2**20:7.1f} M  {name}')

We collect the resident memory, PID, and name of each process and print the five largest. For processes of other users that we may not read, the value in info is None instead of raising an exception. The program shows the memory hogs of a desktop session: an editor and a web browser.

$ python top_memory.py
374 processes
    PID        RSS  NAME
  37945    525.1 M  code
   2798    476.1 M  brave
  38417    467.1 M  kilo
   6718    449.0 M  brave
   7179    405.5 M  brave

Errors

A process can end at any moment, and some information is reserved for its owner or for root. psutil reports these cases with the NoSuchProcess and AccessDenied exceptions.

errors.py
import psutil

print(psutil.pid_exists(1))
print(psutil.pid_exists(4_000_000))

try:
    psutil.Process(4_000_000)
except psutil.NoSuchProcess as e:
    print('error:', e)

init = psutil.Process(1)
print(init.name())

try:
    print(init.environ())
except psutil.AccessDenied as e:
    print('error:', e)

with init.oneshot():
    print(init.username(), init.create_time() < psutil.boot_time() + 60)

The pid_exists function checks whether a PID is in use. Creating a Process for an unknown PID raises NoSuchProcess. Process 1 is systemd, owned by root; an ordinary user can read its name and owner, but not its environment variables. Code that walks over processes should catch both exceptions, because a process may disappear between two calls.

$ python errors.py
True
False
error: process PID not found (pid=4000000)
systemd
error: (pid=1, name='systemd')
root True

Child processes

The psutil.Popen class works like subprocess.Popen, but also has all Process methods. The children method lists the processes started by a process.

children.py
import sys

import psutil

code = 'import time; time.sleep(30)'

parent = psutil.Process()
workers = [psutil.Popen([sys.executable, '-c', code]) for _ in range(3)]

kids = parent.children()
print(len(kids), [k.name() for k in kids])
print(kids[0].cmdline()[1:])

for k in kids:
    k.terminate()

gone, alive = psutil.wait_procs(kids, timeout=3)
print(len(gone), len(alive))
print([p.returncode for p in gone])
print(parent.children())

We start three Python processes that sleep for thirty seconds and terminate them with the SIGTERM signal. The wait_procs function waits up to three seconds and returns the processes that ended and those that are still alive. A negative return code means that the process was killed by a signal; psutil shows it as a Negsignal enum member.

$ python children.py
3 ['python', 'python', 'python']
['-c', 'import time; time.sleep(30)']
3 0
[<Negsignal.SIGTERM: -15>, <Negsignal.SIGTERM: -15>, <Negsignal.SIGTERM: -15>]
[]

Monitoring a process

In the last example we start a child process and sample its CPU usage and memory every half second until it ends.

monitor.py
import sys

import psutil

work = '''
data = []
for i in range(10):
    data.append(bytearray(25 * 2**20))
    sum(range(30_000_000))
'''

child = psutil.Popen([sys.executable, '-c', work])
child.cpu_percent()

print(f'{"time":>5} {"cpu":>6} {"rss":>8}')
t = 0.0

while True:
    try:
        child.wait(timeout=0.5)
        break
    except psutil.TimeoutExpired:
        t += 0.5
    with child.oneshot():
        cpu = child.cpu_percent()
        rss = child.memory_info().rss / 2**20
    print(f'{t:5.1f} {cpu:5.0f}% {rss:6.1f} M')

print('exit code:', child.returncode)

The child allocates 25 MiB per step and does some computation. The first call of cpu_percent without an interval returns a meaningless zero and starts the measurement; each later call returns the usage since the previous call. We use wait with a timeout as the pause between samples, so the loop ends as soon as the child exits. A value slightly over 100 % for a single-threaded process comes from small timing differences between the samples.

$ python monitor.py
 time    cpu      rss
  0.5    98%   74.0 M
  1.0   100%  111.4 M
  1.5   100%  161.4 M
  2.0    98%  211.4 M
  2.5   102%   36.4 M
exit code: 0

Source

psutil documentation

psutil on GitHub

In this article we have read system statistics and inspected, listed, monitored, and terminated processes with psutil. See also Python os module, Python subprocess, Python sys module, and Python rich.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.