Cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python
—
psutil provides numerous constants for platform identification, process states, connection status, and system-specific values. These constants enable cross-platform compatibility and provide meaningful names for system values.
import psutil
# Platform detection constants
print(f"Linux: {psutil.LINUX}") # True on Linux
print(f"Windows: {psutil.WINDOWS}") # True on Windows
print(f"macOS: {psutil.OSX}") # True on macOS
print(f"FreeBSD: {psutil.FREEBSD}") # True on FreeBSD
print(f"OpenBSD: {psutil.OPENBSD}") # True on OpenBSD
print(f"NetBSD: {psutil.NETBSD}") # True on NetBSD
print(f"Sun OS: {psutil.SUNOS}") # True on Solaris/SunOS
print(f"AIX: {psutil.AIX}") # True on AIX
# Platform-specific code
if psutil.LINUX:
print("Running on Linux - can use Linux-specific features")
elif psutil.WINDOWS:
print("Running on Windows - can use Windows-specific features")
elif psutil.OSX:
print("Running on macOS - can use macOS-specific features"){ .api }
# Process status constants
STATUS_RUNNING = psutil.STATUS_RUNNING # Process is running
STATUS_SLEEPING = psutil.STATUS_SLEEPING # Process is sleeping
STATUS_DISK_SLEEP = psutil.STATUS_DISK_SLEEP # Uninterruptible sleep (I/O)
STATUS_STOPPED = psutil.STATUS_STOPPED # Process is stopped
STATUS_TRACING_STOP = psutil.STATUS_TRACING_STOP # Tracing stop
STATUS_ZOMBIE = psutil.STATUS_ZOMBIE # Zombie process
STATUS_DEAD = psutil.STATUS_DEAD # Dead process
STATUS_WAKE_KILL = psutil.STATUS_WAKE_KILL # Wake kill
STATUS_WAKING = psutil.STATUS_WAKING # Waking up
STATUS_IDLE = psutil.STATUS_IDLE # Idle (macOS, FreeBSD)
STATUS_LOCKED = psutil.STATUS_LOCKED # Locked (FreeBSD)
STATUS_WAITING = psutil.STATUS_WAITING # Waiting (FreeBSD)
STATUS_SUSPENDED = psutil.STATUS_SUSPENDED # Suspended (NetBSD)
STATUS_PARKED = psutil.STATUS_PARKED # Parked (Linux)
# Usage example
def get_process_status_name(status):
"""Get human-readable process status name."""
status_names = {
psutil.STATUS_RUNNING: "Running",
psutil.STATUS_SLEEPING: "Sleeping",
psutil.STATUS_DISK_SLEEP: "Disk Sleep",
psutil.STATUS_STOPPED: "Stopped",
psutil.STATUS_ZOMBIE: "Zombie",
psutil.STATUS_DEAD: "Dead",
psutil.STATUS_IDLE: "Idle"
}
return status_names.get(status, f"Unknown ({status})")
# Check process status
for proc in psutil.process_iter(['pid', 'name']):
try:
status = proc.status()
status_name = get_process_status_name(status)
print(f"PID {proc.pid}: {proc.name()} - {status_name}")
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass{ .api }
# Address family constants (socket families)
AF_LINK = psutil.AF_LINK # Link layer (macOS, FreeBSD)
# Connection status constants
CONN_ESTABLISHED = psutil.CONN_ESTABLISHED # Connection established
CONN_SYN_SENT = psutil.CONN_SYN_SENT # SYN sent
CONN_SYN_RECV = psutil.CONN_SYN_RECV # SYN received
CONN_FIN_WAIT1 = psutil.CONN_FIN_WAIT1 # FIN wait 1
CONN_FIN_WAIT2 = psutil.CONN_FIN_WAIT2 # FIN wait 2
CONN_TIME_WAIT = psutil.CONN_TIME_WAIT # Time wait
CONN_CLOSE = psutil.CONN_CLOSE # Closed
CONN_CLOSE_WAIT = psutil.CONN_CLOSE_WAIT # Close wait
CONN_LAST_ACK = psutil.CONN_LAST_ACK # Last ACK
CONN_LISTEN = psutil.CONN_LISTEN # Listening
CONN_CLOSING = psutil.CONN_CLOSING # Closing
CONN_NONE = psutil.CONN_NONE # No status
# Usage example
def analyze_connections():
"""Analyze network connections by status."""
status_count = {}
for conn in psutil.net_connections():
status = conn.status
status_count[status] = status_count.get(status, 0) + 1
print("Connection status summary:")
for status, count in status_count.items():
print(f" {status}: {count}")
# analyze_connections(){ .api }
# Network interface duplex constants
NIC_DUPLEX_FULL = psutil.NIC_DUPLEX_FULL # Full duplex
NIC_DUPLEX_HALF = psutil.NIC_DUPLEX_HALF # Half duplex
NIC_DUPLEX_UNKNOWN = psutil.NIC_DUPLEX_UNKNOWN # Unknown duplex
# Usage example
def check_interface_duplex():
"""Check network interface duplex settings."""
stats = psutil.net_if_stats()
for interface, stat in stats.items():
if hasattr(stat, 'duplex'):
duplex_name = {
psutil.NIC_DUPLEX_FULL: "Full",
psutil.NIC_DUPLEX_HALF: "Half",
psutil.NIC_DUPLEX_UNKNOWN: "Unknown"
}.get(stat.duplex, "N/A")
print(f"{interface}: {duplex_name} duplex")
# check_interface_duplex(){ .api }
# Power time constants
POWER_TIME_UNKNOWN = psutil.POWER_TIME_UNKNOWN # Unknown time remaining
POWER_TIME_UNLIMITED = psutil.POWER_TIME_UNLIMITED # Unlimited (plugged in)
# Usage example
def format_battery_time(seconds):
"""Format battery time with proper handling of special values."""
if seconds == psutil.POWER_TIME_UNKNOWN:
return "Unknown"
elif seconds == psutil.POWER_TIME_UNLIMITED:
return "Unlimited (plugged in)"
else:
hours, remainder = divmod(seconds, 3600)
minutes, _ = divmod(remainder, 60)
return f"{hours}h {minutes}m"
# Check battery status
try:
battery = psutil.sensors_battery()
if battery:
time_str = format_battery_time(battery.secsleft)
print(f"Battery: {battery.percent}%, Time remaining: {time_str}")
except AttributeError:
print("Battery information not available"){ .api }
if psutil.LINUX:
# I/O scheduling class constants (Linux only)
IOPRIO_CLASS_NONE = psutil.IOPRIO_CLASS_NONE # No specific I/O class
IOPRIO_CLASS_RT = psutil.IOPRIO_CLASS_RT # Real-time I/O class
IOPRIO_CLASS_BE = psutil.IOPRIO_CLASS_BE # Best-effort I/O class
IOPRIO_CLASS_IDLE = psutil.IOPRIO_CLASS_IDLE # Idle I/O class
# Usage example
def set_process_ionice(pid, ioclass, value=0):
"""Set process I/O priority on Linux."""
try:
p = psutil.Process(pid)
p.ionice(ioclass, value)
print(f"Set I/O priority for PID {pid}: class={ioclass}, value={value}")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
print(f"Error setting I/O priority: {e}")
# Set current process to idle I/O class
# set_process_ionice(psutil.Process().pid, psutil.IOPRIO_CLASS_IDLE){ .api }
if hasattr(psutil, 'RLIMIT_NOFILE'):
# Resource limit constants (Unix-like systems)
# Basic resource limits (available on most Unix-like systems)
RLIMIT_AS = psutil.RLIMIT_AS # Address space limit
RLIMIT_CORE = psutil.RLIMIT_CORE # Core dump size limit
RLIMIT_CPU = psutil.RLIMIT_CPU # CPU time limit
RLIMIT_DATA = psutil.RLIMIT_DATA # Data segment size limit
RLIMIT_FSIZE = psutil.RLIMIT_FSIZE # File size limit
RLIMIT_MEMLOCK = psutil.RLIMIT_MEMLOCK # Locked memory limit
RLIMIT_NOFILE = psutil.RLIMIT_NOFILE # Number of open files limit
RLIMIT_NPROC = psutil.RLIMIT_NPROC # Number of processes limit
RLIMIT_RSS = psutil.RLIMIT_RSS # RSS memory limit
RLIMIT_STACK = psutil.RLIMIT_STACK # Stack size limit
# Linux-specific resource limits
if hasattr(psutil, 'RLIMIT_LOCKS'):
RLIMIT_LOCKS = psutil.RLIMIT_LOCKS # File locks limit (Linux)
if hasattr(psutil, 'RLIMIT_MSGQUEUE'):
RLIMIT_MSGQUEUE = psutil.RLIMIT_MSGQUEUE # Message queue bytes (Linux)
if hasattr(psutil, 'RLIMIT_NICE'):
RLIMIT_NICE = psutil.RLIMIT_NICE # Nice priority limit (Linux)
if hasattr(psutil, 'RLIMIT_RTPRIO'):
RLIMIT_RTPRIO = psutil.RLIMIT_RTPRIO # Real-time priority (Linux)
if hasattr(psutil, 'RLIMIT_RTTIME'):
RLIMIT_RTTIME = psutil.RLIMIT_RTTIME # Real-time CPU time (Linux)
if hasattr(psutil, 'RLIMIT_SIGPENDING'):
RLIMIT_SIGPENDING = psutil.RLIMIT_SIGPENDING # Pending signals (Linux)
# FreeBSD-specific resource limits
if hasattr(psutil, 'RLIMIT_SWAP'):
RLIMIT_SWAP = psutil.RLIMIT_SWAP # Swap space (FreeBSD)
if hasattr(psutil, 'RLIMIT_SBSIZE'):
RLIMIT_SBSIZE = psutil.RLIMIT_SBSIZE # Socket buffer size (FreeBSD)
if hasattr(psutil, 'RLIMIT_NPTS'):
RLIMIT_NPTS = psutil.RLIMIT_NPTS # Pseudo-terminals (FreeBSD)
# RLIM_INFINITY constant
if hasattr(psutil, 'RLIM_INFINITY'):
RLIM_INFINITY = psutil.RLIM_INFINITY # Unlimited resource value
# Usage example
def check_resource_limits(pid=None):
"""Check resource limits for a process."""
try:
p = psutil.Process(pid)
limits_to_check = [
('NOFILE', psutil.RLIMIT_NOFILE, "Open files"),
('NPROC', psutil.RLIMIT_NPROC, "Processes"),
('STACK', psutil.RLIMIT_STACK, "Stack size"),
('DATA', psutil.RLIMIT_DATA, "Data segment"),
]
print(f"Resource limits for PID {p.pid}:")
for name, constant, description in limits_to_check:
try:
soft, hard = p.rlimit(constant)
print(f" {description}: soft={soft}, hard={hard}")
except (AttributeError, OSError):
print(f" {description}: Not available")
except psutil.NoSuchProcess:
print("Process not found")
# Check limits for current process
# check_resource_limits(){ .api }
if psutil.WINDOWS:
# Windows process priority constants
try:
ABOVE_NORMAL_PRIORITY_CLASS = psutil.ABOVE_NORMAL_PRIORITY_CLASS
BELOW_NORMAL_PRIORITY_CLASS = psutil.BELOW_NORMAL_PRIORITY_CLASS
HIGH_PRIORITY_CLASS = psutil.HIGH_PRIORITY_CLASS
IDLE_PRIORITY_CLASS = psutil.IDLE_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS = psutil.NORMAL_PRIORITY_CLASS
REALTIME_PRIORITY_CLASS = psutil.REALTIME_PRIORITY_CLASS
# Usage example
def set_windows_priority(pid, priority_class):
"""Set Windows process priority."""
try:
p = psutil.Process(pid)
p.nice(priority_class)
print(f"Set priority for PID {pid} to {priority_class}")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
print(f"Error setting priority: {e}")
except AttributeError:
print("Windows priority constants not available")
# I/O Priority Constants
### Windows I/O Priority
```python
if psutil.WINDOWS:
# Windows I/O priority constants
try:
IOPRIO_VERYLOW = psutil.IOPRIO_VERYLOW # Very low I/O priority
IOPRIO_LOW = psutil.IOPRIO_LOW # Low I/O priority
IOPRIO_NORMAL = psutil.IOPRIO_NORMAL # Normal I/O priority
IOPRIO_HIGH = psutil.IOPRIO_HIGH # High I/O priority
# Usage example
def set_io_priority(pid, io_class):
"""Set Windows process I/O priority."""
try:
p = psutil.Process(pid)
p.ionice(io_class)
print(f"Set I/O priority for PID {pid} to {io_class}")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
print(f"Error setting I/O priority: {e}")
except AttributeError:
print("Windows I/O priority constants not available"){ .api }
if psutil.LINUX:
# Linux I/O scheduling class constants
try:
IOPRIO_CLASS_NONE = psutil.IOPRIO_CLASS_NONE # No specific I/O class
IOPRIO_CLASS_RT = psutil.IOPRIO_CLASS_RT # Real-time I/O class
IOPRIO_CLASS_BE = psutil.IOPRIO_CLASS_BE # Best-effort I/O class
IOPRIO_CLASS_IDLE = psutil.IOPRIO_CLASS_IDLE # Idle I/O class
# Usage example
def set_linux_io_priority(pid, io_class, value=4):
"""Set Linux process I/O priority."""
try:
p = psutil.Process(pid)
p.ionice(io_class, value) # value 0-7 for BE/RT classes
print(f"Set I/O class {io_class} with value {value} for PID {pid}")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
print(f"Error setting I/O priority: {e}")
except AttributeError:
print("Linux I/O priority constants not available"){ .api }
# Socket type constants (platform-dependent)
if hasattr(psutil, 'AF_LINK'):
AF_LINK = psutil.AF_LINK # Link layer interface (BSD, macOS)
# Usage in connection filtering
def filter_connections_by_family():
"""Filter connections by address family."""
connections = psutil.net_connections()
family_count = {}
for conn in connections:
family = conn.family
family_count[family] = family_count.get(family, 0) + 1
print("Connections by address family:")
for family, count in family_count.items():
family_name = {
2: "IPv4", # socket.AF_INET
10: "IPv6", # socket.AF_INET6 (on most systems)
}.get(family, f"Family {family}")
print(f" {family_name}: {count}")
# filter_connections_by_family(){ .api }
def check_constant_availability():
"""Check which constants are available on current platform."""
constants_to_check = [
# Platform constants
('LINUX', 'psutil.LINUX'),
('WINDOWS', 'psutil.WINDOWS'),
('OSX', 'psutil.OSX'),
# Status constants
('STATUS_RUNNING', 'psutil.STATUS_RUNNING'),
('STATUS_ZOMBIE', 'psutil.STATUS_ZOMBIE'),
# Connection constants
('CONN_ESTABLISHED', 'psutil.CONN_ESTABLISHED'),
('CONN_LISTEN', 'psutil.CONN_LISTEN'),
# Power constants
('POWER_TIME_UNKNOWN', 'psutil.POWER_TIME_UNKNOWN'),
# Linux-specific
('IOPRIO_CLASS_IDLE', 'psutil.IOPRIO_CLASS_IDLE'),
('RLIMIT_NOFILE', 'psutil.RLIMIT_NOFILE'),
# Windows-specific
('HIGH_PRIORITY_CLASS', 'psutil.HIGH_PRIORITY_CLASS'),
]
print("Constant availability check:")
for name, attr_path in constants_to_check:
try:
# Use getattr with module path
parts = attr_path.split('.')
obj = psutil
for part in parts[1:]: # Skip 'psutil'
obj = getattr(obj, part)
print(f" {name}: Available ({obj})")
except AttributeError:
print(f" {name}: Not available")
# Check what constants are available
check_constant_availability(){ .api }
def safe_get_process_info(pid):
"""Safely get process info with platform-aware constant usage."""
try:
p = psutil.Process(pid)
info = {
'pid': p.pid,
'name': p.name(),
'status': p.status()
}
# Add platform-specific info
if psutil.LINUX and hasattr(p, 'ionice'):
try:
ionice = p.ionice()
info['ionice_class'] = ionice.ioclass
info['ionice_value'] = ionice.value
except (AttributeError, psutil.AccessDenied):
pass
if psutil.WINDOWS and hasattr(p, 'nice'):
try:
info['priority'] = p.nice()
except psutil.AccessDenied:
pass
return info
except psutil.NoSuchProcess:
return None
# Get process info safely across platforms
info = safe_get_process_info(psutil.Process().pid)
if info:
print("Process info:", info){ .api }
def get_system_capabilities():
"""Determine system capabilities based on available constants."""
capabilities = {
'platform': None,
'process_priority': False,
'io_priority': False,
'resource_limits': False,
'battery_info': False,
'sensors': False
}
# Detect platform
if psutil.LINUX:
capabilities['platform'] = 'Linux'
capabilities['io_priority'] = hasattr(psutil, 'IOPRIO_CLASS_IDLE')
capabilities['resource_limits'] = hasattr(psutil, 'RLIMIT_NOFILE')
elif psutil.WINDOWS:
capabilities['platform'] = 'Windows'
capabilities['process_priority'] = hasattr(psutil, 'HIGH_PRIORITY_CLASS')
elif psutil.OSX:
capabilities['platform'] = 'macOS'
# Check sensor capabilities
capabilities['battery_info'] = hasattr(psutil, 'sensors_battery')
capabilities['sensors'] = hasattr(psutil, 'sensors_temperatures')
return capabilities
# Get system capabilities
caps = get_system_capabilities()
print("System capabilities:", caps){ .api }
Install with Tessl CLI
npx tessl i tessl/pypi-psutil