Python psutil System Monitoring — Core Concepts

What psutil does

psutil (process and system utilities) is a cross-platform Python library that retrieves information about running processes and system utilization. It works on Linux, macOS, Windows, FreeBSD, and other platforms through a single, consistent API.

Think of it as a universal translator between your Python code and the operating system’s low-level system calls. Instead of parsing /proc/meminfo on Linux, calling GlobalMemoryStatusEx on Windows, or using sysctl on macOS, you write psutil.virtual_memory() and get the same structured result everywhere.

The four pillars of system monitoring

CPU

import psutil

# Overall CPU usage as a percentage (averaged over 1 second)
psutil.cpu_percent(interval=1)

# Per-core usage
psutil.cpu_percent(interval=1, percpu=True)

# Detailed CPU times (user, system, idle, iowait, etc.)
psutil.cpu_times()

# Number of logical and physical cores
psutil.cpu_count(logical=True)
psutil.cpu_count(logical=False)

The interval parameter in cpu_percent() matters. Without it, the function compares against the last call, which can produce misleading numbers if calls are irregular. Setting interval=1 blocks for one second and gives an accurate snapshot.

Memory

mem = psutil.virtual_memory()
mem.total       # Total physical memory in bytes
mem.available   # Memory that can be given to processes without swapping
mem.percent     # Percentage used
mem.used        # Memory actively in use
mem.cached      # Memory used for caching (Linux)

A common misconception: “used memory” is not the same as “unavailable memory.” Linux aggressively caches disk data in RAM, so used often looks high even when plenty of memory is available. psutil’s available field accounts for this, making it the right metric to check whether your system is actually under memory pressure.

Disk

# Disk usage for a specific path
usage = psutil.disk_usage('/')
usage.total
usage.used
usage.free
usage.percent

# All mounted partitions
for part in psutil.disk_partitions():
    print(part.mountpoint, part.fstype)

# I/O counters (reads, writes, bytes)
psutil.disk_io_counters()

Network

# Network I/O counters
net = psutil.net_io_counters()
net.bytes_sent
net.bytes_recv

# Per-interface counters
psutil.net_io_counters(pernic=True)

# Active network connections
psutil.net_connections(kind='inet')

How it works under the hood

psutil does not run shell commands or scrape text output. It makes direct system calls through C extension modules compiled for each platform. On Linux, it reads from the /proc and /sys virtual filesystems. On Windows, it calls Win32 APIs. On macOS, it uses sysctl and Mach kernel calls.

This approach is faster and more reliable than shelling out to tools like top or free, and it avoids the fragility of parsing human-readable output that can change between OS versions.

Process monitoring

Beyond system-wide metrics, psutil can inspect individual processes:

for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
    if proc.info['cpu_percent'] > 50:
        print(f"High CPU: {proc.info['name']} (PID {proc.info['pid']})")

The process_iter() function is designed for efficiency — it caches process information and handles processes that disappear mid-iteration without raising exceptions.

Common misconception

Many beginners call psutil.cpu_percent() once without an interval and get 0.0 back. This happens because the function needs two measurement points to calculate a percentage. Either pass interval=1 for a blocking measurement, or call it repeatedly in a loop and use the values from the second call onward.

Practical use cases

  • Alerting scripts that notify you when CPU, memory, or disk crosses a threshold
  • Resource dashboards that poll metrics every few seconds and display trends
  • Auto-scaling triggers that spin up new workers when system load is high
  • Runaway process killers that terminate processes exceeding memory or CPU limits
  • Capacity planning tools that log utilization over days or weeks to spot growth trends

One thing to remember: psutil gives you a portable, Pythonic API for the same system metrics that tools like top, htop, free, and df provide — but available programmatically for automation, alerting, and dashboards.

pythonmonitoringsystem-administrationdevops

See Also

  • Python Crontab Management How Python can set up automatic timers on your computer — like programming an alarm clock that runs tasks instead of waking you up.
  • Python Disk Usage Monitoring How Python helps you keep an eye on your computer's storage — like a fuel gauge that warns you before you run out of space.
  • Python Log Rotation Management Why your program's diary needs page limits — and how Python keeps log files from eating all your disk space.
  • Python Network Interface Monitoring How Python watches your computer's network connections — like having a traffic counter on every road leading to your house.
  • Python Process Management How Python lets you see and control all the programs running on your computer — like being the manager of a busy office.