Of course! The psutil (Process and System Utilities) library is a powerful and cross-platform library for Python that provides an easy way to retrieve information on running processes and system utilization (CPU, memory, disks, network, etc.).
It's a must-have for system monitoring, profiling, and automation tasks.
Here's a comprehensive guide to the psutil API, broken down by category with clear examples.
Installation
First, you need to install the library. It's available on PyPI.
pip install psutil
Core Concepts
- Cross-Platform: Works on Windows, Linux, macOS, and FreeBSD.
- Process Objects: Many functions return a
psutil.Processobject, which represents a single running process. This object has methods to get detailed information about that specific process (e.g., its CPU usage, memory, open files). - Named Tuples: Information like disk I/O or network connections is often returned as a
namedtuple, which is like a lightweight object you can access with either index or attribute (e.g.,result[0]orresult.name).
System-wide Information
These functions provide a high-level overview of the entire system.
CPU Information
import psutil
# Get CPU percent usage, blocking for a second to get a real value
print(f"CPU Usage: {psutil.cpu_percent(interval=1)}%")
# Get per-logical CPU core usage
print(f"CPU Core Usage: {psutil.cpu_percent(interval=1, percpu=True)}")
# Get number of logical (hyper-threaded) and physical cores
print(f"Logical CPUs: {psutil.cpu_count(logical=True)}")
print(f"Physical CPUs: {psutil.cpu_count(logical=False)}")
# Get CPU frequency information (in MHz)
cpu_freq = psutil.cpu_freq()
print(f"Current CPU Frequency: {cpu_freq.current} MHz")
print(f"Min/Max CPU Frequency: {cpu_freq.min} MHz / {cpu_freq.max} MHz")
Memory Information
import psutil
# Get virtual memory information (RAM)
mem = psutil.virtual_memory()
print("--- Virtual Memory (RAM) ---")
print(f"Total: {mem.total / (1024**3):.2f} GB")
print(f"Available: {mem.available / (1024**3):.2f} GB") # Memory that can be given instantly to processes
print(f"Used: {mem.used / (1024**3):.2f} GB")
print(f"Percentage: {mem.percent}%")
# Get swap memory (page file) information
swap = psutil.swap_memory()
print("\n--- Swap Memory ---")
print(f"Total: {swap.total / (1024**3):.2f} GB")
print(f"Used: {swap.used / (1024**3):.2f} GB")
print(f"Free: {swap.free / (1024**3):.2f} GB")
print(f"Percentage: {swap.percent}%")
Disk Information
import psutil
# Get disk partition information
print("--- Disk Partitions ---")
for partition in psutil.disk_partitions():
print(f"Device: {partition.device}, Mountpoint: {partition.mountpoint}, Filesystem: {partition.fstype}")
# Get disk usage statistics for a specific path (e.g., root '/')
print("\n--- Disk Usage for '/' ---")
disk_usage = psutil.disk_usage('/')
print(f"Total: {disk_usage.total / (1024**3):.2f} GB")
print(f"Used: {disk_usage.used / (1024**3):.2f} GB")
print(f"Free: {disk_usage.free / (1024**3):.2f} GB")
# Get disk I/O statistics
print("\n--- Disk I/O Statistics ---")
disk_io = psutil.disk_io_counters(perdisk=True)
for device, counters in disk_io.items():
print(f"Device {device}: Read Bytes={counters.read_bytes}, Write Bytes={counters.write_bytes}")
Network Information
import psutil
# Get network I/O statistics
print("--- Network I/O Statistics ---")
net_io = psutil.net_io_counters(pernic=True)
for interface, counters in net_io.items():
print(f"Interface {interface}: Bytes Sent={counters.bytes_sent}, Bytes Recv={counters.bytes_recv}")
# Get network connections
print("\n--- Network Connections ---")
# kind can be 'inet' (IPv4), 'inet6' (IPv6), 'tcp', 'udp', 'unix', etc.
connections = psutil.net_connections(kind='inet')
for conn in connections[:5]: # Print first 5 to avoid flooding the console
if conn.status: # Only show established or other interesting connections
print(f"Local: {conn.laddr}, Remote: {conn.raddr}, Status: {conn.status}")
Process Information
This is one of the most powerful features of psutil.
Getting a Process Object
import psutil
import time
# Get all running processes
all_processes = psutil.process_iter(['pid', 'name'])
# Find a specific process, for example, the current Python script
current_pid = os.getpid()
try:
# Get process by PID
p = psutil.Process(current_pid)
print(f"Found current process: {p.name()} (PID: {p.pid})")
# Iterate through all processes to find one by name
for proc in psutil.process_iter(['name']):
if proc.info['name'] == 'chrome.exe':
print(f"Found Chrome process: {proc.info} (PID: {proc.pid})")
break
except psutil.NoSuchProcess:
print("Process with PID {} not found".format(current_pid))
psutil.Process Methods and Attributes
Once you have a Process object, you can query it for detailed information.
import psutil
import os
p = psutil.Process(os.getpid())
# --- Basic Info ---
print(f"Name: {p.name()}")
print(f"PID: {p.pid}")
print(f"Parent PID: {p.ppid()}")
print(f"Status: {p.status()}") # running, sleeping, zombie, etc.
print(f"Username: {p.username()}")
# --- CPU Usage ---
# Get CPU percent for this process since the last call
print(f"CPU Percent (this process): {p.cpu_percent(interval=1)}%")
# Get cumulative CPU time (user, system)
print(f"CPU Times: {p.cpu_times()}")
# --- Memory Usage ---
# Get memory information for this process (RSS and VMS)
# rss = Resident Set Size (actual physical memory used)
# vms = Virtual Memory Size (total virtual memory used)
print(f"Memory Info: {p.memory_info()}")
# Get memory as a percentage of the total system memory
print(f"Memory Percent: {p.memory_percent()}%")
# --- I/O Usage ---
# Get number of I/O operations (read/write)
print(f"I/O Counters: {p.io_counters()}")
# --- Open Files and Connections ---
# List files opened by the process
try:
open_files = p.open_files()
if open_files:
print(f"Open Files: {[f.path for f in open_files]}")
else:
print("No open files.")
except psutil.AccessDenied:
print("Access denied to get open files.")
# List network connections for the process
try:
connections = p.connections()
if connections:
print(f"Connections: {connections}")
else:
print("No open network connections.")
except psutil.AccessDenied:
print("Access denied to get connections.")
# --- Children Processes ---
# Get child processes of this process
children = p.children(recursive=True)
if children:
print(f"Child processes: {[c.pid for c in children]}")
else:
print("No child processes.")
# --- Terminate a Process ---
# Be careful with this! Uncomment to test.
# print(f"Terminating process {p.pid}...")
# p.terminate() # Sends SIGTERM
# time.sleep(2)
# print(f"Process status after terminate: {p.status()}")
# For a force kill (use with extreme caution)
# p.kill() # Sends SIGKILL
Practical Example: A System Monitor
Here's a simple script that continuously prints the system's CPU, memory, and disk usage.
import psutil
import time
def monitor_system(interval=5):
"""Continuously monitors and prints system stats."""
try:
while True:
# --- CPU ---
cpu_percent = psutil.cpu_percent(interval=interval)
cpu_cores = psutil.cpu_percent(interval=interval, percpu=True)
# --- Memory ---
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
# --- Disk ---
disk = psutil.disk_usage('/')
# --- Clear screen for a "live" effect (works on Linux/macOS/Windows) ---
print("\033[H\033[J", end="")
print("="*40, "System Monitor", "="*40)
print(f"CPU Usage: {cpu_percent:.1f}%")
print(f"Per-Core Usage: {', '.join(f'{core:.1f}%' for core in cpu_cores)}")
print("-"*40)
print(f"Memory Usage: {mem.percent:.1f}% ({mem.used / (1024**3):.2f}GB / {mem.total / (1024**3):.2f}GB)")
print(f"Swap Usage: {swap.percent:.1f}% ({swap.used / (1024**3):.2f}GB / {swap.total / (1024**3):.2f}GB)")
print("-"*40)
print(f"Disk Usage ('/'): {disk.percent:.1f}% ({disk.used / (1024**3):.2f}GB / {disk.total / (1024**3):.2f}GB)")
print("="*80)
except KeyboardInterrupt:
print("\nMonitoring stopped by user.")
# Run the monitor
if __name__ == "__main__":
monitor_system(interval=2)
Summary Table
| Category | Key Functions / Attributes |
|---|---|
| System Info | psutil.cpu_percent(), psutil.cpu_count(), psutil.virtual_memory(), psutil.disk_usage() |
| Process Info | psutil.process_iter(), psutil.Process(pid), p.name(), p.status(), p.cpu_percent() |
| Memory | p.memory_info(), p.memory_percent(), psutil.swap_memory() |
| Disk I/O | psutil.disk_io_counters(perdisk=True) |
| Network | psutil.net_io_counters(pernic=True), p.connections() |
| Process Control | p.terminate(), p.kill(), p.suspend(), p.resume(), p.children() |
For the most complete and up-to-date information, always refer to the official psutil documentation.
