Cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python
—
psutil provides comprehensive system-wide monitoring functions for CPU, memory, disk, network, and general system information. These module-level functions complement the Process class for complete system monitoring.
import psutil
# CPU count
logical_cpus = psutil.cpu_count() # Logical CPUs (including hyperthreading)
physical_cpus = psutil.cpu_count(logical=False) # Physical CPU cores only
# CPU frequency (if supported)
if hasattr(psutil, 'cpu_freq'):
freq = psutil.cpu_freq() # Current, min, max frequency
per_cpu_freq = psutil.cpu_freq(percpu=True) # Per-CPU frequency info{ .api }
# CPU usage percentage
cpu_percent = psutil.cpu_percent() # Overall CPU usage
cpu_percent_interval = psutil.cpu_percent(interval=1) # With measurement interval
per_cpu_percent = psutil.cpu_percent(percpu=True) # Per-CPU usage
# CPU times
cpu_times = psutil.cpu_times() # Overall CPU times
per_cpu_times = psutil.cpu_times(percpu=True) # Per-CPU times
# CPU statistics
cpu_stats = psutil.cpu_stats() # Context switches, interrupts, soft interrupts
# CPU time percentages (detailed breakdown)
cpu_times_percent = psutil.cpu_times_percent() # Overall CPU time percentages
cpu_times_percent_interval = psutil.cpu_times_percent(interval=1) # With measurement interval
per_cpu_times_percent = psutil.cpu_times_percent(percpu=True) # Per-CPU time percentages{ .api }
# System load average (Unix platforms with getloadavg support)
if hasattr(psutil, 'getloadavg'):
load1, load5, load15 = psutil.getloadavg()
print(f"Load average: {load1:.2f}, {load5:.2f}, {load15:.2f}")
else:
print("Load average not available on this platform"){ .api }
# System memory usage
memory = psutil.virtual_memory()
print(f"Total: {memory.total / 1024**3:.2f} GB")
print(f"Available: {memory.available / 1024**3:.2f} GB")
print(f"Used: {memory.used / 1024**3:.2f} GB")
print(f"Percentage: {memory.percent}%")
print(f"Free: {memory.free / 1024**3:.2f} GB")
# Additional memory fields (platform-specific)
if hasattr(memory, 'buffers'):
print(f"Buffers: {memory.buffers / 1024**3:.2f} GB")
if hasattr(memory, 'cached'):
print(f"Cached: {memory.cached / 1024**3:.2f} GB"){ .api }
# Swap memory information
swap = psutil.swap_memory()
print(f"Swap Total: {swap.total / 1024**3:.2f} GB")
print(f"Swap Used: {swap.used / 1024**3:.2f} GB")
print(f"Swap Free: {swap.free / 1024**3:.2f} GB")
print(f"Swap Percentage: {swap.percent}%")
print(f"Swap In: {swap.sin}") # Bytes swapped in
print(f"Swap Out: {swap.sout}") # Bytes swapped out{ .api }
# Disk usage for specific path
usage = psutil.disk_usage('/') # Unix root
# usage = psutil.disk_usage('C:\\') # Windows C: drive
print(f"Total: {usage.total / 1024**3:.2f} GB")
print(f"Used: {usage.used / 1024**3:.2f} GB")
print(f"Free: {usage.free / 1024**3:.2f} GB")
print(f"Percentage: {(usage.used / usage.total) * 100:.1f}%"){ .api }
# List all disk partitions
partitions = psutil.disk_partitions()
for partition in partitions:
print(f"Device: {partition.device}")
print(f"Mountpoint: {partition.mountpoint}")
print(f"Filesystem: {partition.fstype}")
print(f"Options: {partition.opts}")
# Get usage for each partition
try:
usage = psutil.disk_usage(partition.mountpoint)
print(f" Total: {usage.total / 1024**3:.2f} GB")
print(f" Used: {usage.used / 1024**3:.2f} GB")
print(f" Free: {usage.free / 1024**3:.2f} GB")
except PermissionError:
print(" Permission denied"){ .api }
# System-wide disk I/O
disk_io = psutil.disk_io_counters()
if disk_io:
print(f"Read bytes: {disk_io.read_bytes}")
print(f"Write bytes: {disk_io.write_bytes}")
print(f"Read count: {disk_io.read_count}")
print(f"Write count: {disk_io.write_count}")
print(f"Read time: {disk_io.read_time} ms")
print(f"Write time: {disk_io.write_time} ms")
# Per-disk I/O statistics
per_disk_io = psutil.disk_io_counters(perdisk=True)
for device, io in per_disk_io.items():
print(f"{device}: R={io.read_bytes} W={io.write_bytes}"){ .api }
# System-wide network I/O
net_io = psutil.net_io_counters()
print(f"Bytes sent: {net_io.bytes_sent}")
print(f"Bytes received: {net_io.bytes_recv}")
print(f"Packets sent: {net_io.packets_sent}")
print(f"Packets received: {net_io.packets_recv}")
# Per-interface network I/O
per_nic_io = psutil.net_io_counters(pernic=True)
for interface, io in per_nic_io.items():
print(f"{interface}: TX={io.bytes_sent} RX={io.bytes_recv}"){ .api }
# Network interface addresses
addrs = psutil.net_if_addrs()
for interface, addr_list in addrs.items():
print(f"Interface: {interface}")
for addr in addr_list:
print(f" Family: {addr.family}")
print(f" Address: {addr.address}")
if addr.netmask:
print(f" Netmask: {addr.netmask}")
if addr.broadcast:
print(f" Broadcast: {addr.broadcast}")
# Network interface statistics
stats = psutil.net_if_stats()
for interface, stat in stats.items():
print(f"{interface}: Up={stat.isup}, Speed={stat.speed}Mb/s, MTU={stat.mtu}"){ .api }
# System-wide network connections
connections = psutil.net_connections()
for conn in connections[:5]: # Show first 5
print(f"Protocol: {conn.type}")
print(f"Local: {conn.laddr}")
print(f"Remote: {conn.raddr}")
print(f"Status: {conn.status}")
print(f"PID: {conn.pid}")
# Filter by connection type
tcp_connections = psutil.net_connections(kind='tcp')
udp_connections = psutil.net_connections(kind='udp')
inet_connections = psutil.net_connections(kind='inet') # TCP + UDP{ .api }
import datetime
# System boot time
boot_timestamp = psutil.boot_time()
boot_time = datetime.datetime.fromtimestamp(boot_timestamp)
print(f"Boot time: {boot_time}")
# System uptime
uptime_seconds = psutil.time.time() - boot_timestamp
uptime_string = str(datetime.timedelta(seconds=uptime_seconds))
print(f"Uptime: {uptime_string}"){ .api }
# Currently logged in users
users = psutil.users()
for user in users:
print(f"User: {user.name}")
print(f"Terminal: {user.terminal}")
print(f"Host: {user.host}")
print(f"Started: {datetime.datetime.fromtimestamp(user.started)}"){ .api }
def system_overview():
"""Get comprehensive system information."""
info = {}
# CPU
info['cpu'] = {
'count_logical': psutil.cpu_count(),
'count_physical': psutil.cpu_count(logical=False),
'usage_percent': psutil.cpu_percent(interval=1),
'frequency': psutil.cpu_freq()._asdict() if hasattr(psutil, 'cpu_freq') and psutil.cpu_freq() else None
}
# Memory
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
info['memory'] = {
'virtual': memory._asdict(),
'swap': swap._asdict()
}
# Disk
info['disk'] = {}
for partition in psutil.disk_partitions():
try:
usage = psutil.disk_usage(partition.mountpoint)
info['disk'][partition.device] = {
'mountpoint': partition.mountpoint,
'fstype': partition.fstype,
'usage': usage._asdict()
}
except PermissionError:
pass
# Network
net_io = psutil.net_io_counters()
info['network'] = {
'io': net_io._asdict() if net_io else None,
'interfaces': list(psutil.net_if_addrs().keys())
}
# System
info['system'] = {
'boot_time': psutil.boot_time(),
'users': len(psutil.users())
}
return info
# Get system overview
overview = system_overview(){ .api }
import time
def monitor_system(duration=60, interval=5):
"""Monitor system resources for specified duration."""
start_time = time.time()
print(f"{'Time':<8} {'CPU%':<6} {'Memory%':<8} {'Disk R/s':<10} {'Disk W/s':<10} {'Net RX':<10} {'Net TX':<10}")
print("-" * 70)
# Get initial values for rate calculations
prev_disk = psutil.disk_io_counters()
prev_net = psutil.net_io_counters()
prev_time = time.time()
while time.time() - start_time < duration:
# Current measurements
cpu_percent = psutil.cpu_percent(interval=1)
memory_percent = psutil.virtual_memory().percent
curr_disk = psutil.disk_io_counters()
curr_net = psutil.net_io_counters()
curr_time = time.time()
# Calculate rates
time_delta = curr_time - prev_time
if prev_disk and curr_disk and time_delta > 0:
disk_read_rate = (curr_disk.read_bytes - prev_disk.read_bytes) / time_delta
disk_write_rate = (curr_disk.write_bytes - prev_disk.write_bytes) / time_delta
else:
disk_read_rate = disk_write_rate = 0
if prev_net and curr_net and time_delta > 0:
net_recv_rate = (curr_net.bytes_recv - prev_net.bytes_recv) / time_delta
net_sent_rate = (curr_net.bytes_sent - prev_net.bytes_sent) / time_delta
else:
net_recv_rate = net_sent_rate = 0
# Display
timestamp = time.strftime("%H:%M:%S")
print(f"{timestamp:<8} {cpu_percent:<6.1f} {memory_percent:<8.1f} "
f"{disk_read_rate/1024:<10.0f} {disk_write_rate/1024:<10.0f} "
f"{net_recv_rate/1024:<10.0f} {net_sent_rate/1024:<10.0f}")
# Update previous values
prev_disk, prev_net, prev_time = curr_disk, curr_net, curr_time
time.sleep(interval)
# Monitor system for 5 minutes
# monitor_system(duration=300, interval=5){ .api }
# Test function - displays system information in ps-like format
psutil.test() # Prints comprehensive system/process overview to stdout
# Version information
print(f"psutil version: {psutil.__version__}")
print(f"Version info tuple: {psutil.version_info}")
# Debug mode (for development/troubleshooting)
psutil._set_debug(True) # Enable debug output to stderr
psutil._set_debug(False) # Disable debug output{ .api }
if psutil.LINUX:
# Additional Linux-specific system info
try:
# CPU stats include more detailed info on Linux
cpu_stats = psutil.cpu_stats()
print(f"Context switches: {cpu_stats.ctx_switches}")
print(f"Interrupts: {cpu_stats.interrupts}")
print(f"Soft interrupts: {cpu_stats.soft_interrupts}")
print(f"System calls: {cpu_stats.syscalls}")
except AttributeError:
pass{ .api }
if psutil.WINDOWS:
# Windows Services Management
# List all Windows services
for service in psutil.win_service_iter():
print(f"Service: {service.name()}")
print(f"Display name: {service.display_name()}")
print(f"Status: {service.status()}")
# Get specific service by name
try:
service = psutil.win_service_get('wuauserv') # Windows Update service
print(f"Service info: {service.as_dict()}")
print(f"Status: {service.status()}")
print(f"Start type: {service.start_type()}")
print(f"Username: {service.username()}")
except psutil.NoSuchProcess:
print("Service not found"){ .api }
interval parameters with CPU monitoring functions for accurate measurementsInstall with Tessl CLI
npx tessl i tessl/pypi-psutil