Cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python
npx @tessl/cli install tessl/pypi-psutil@7.0.00
# psutil
1
2
Cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.
3
4
## Package Information
5
6
**Name:** `psutil`
7
**Language:** Python
8
**Installation:** `pip install psutil`
9
**Platforms:** Linux, Windows, macOS, FreeBSD, OpenBSD, NetBSD, AIX, Solaris
10
11
## Core Imports
12
13
```python
14
import psutil
15
from psutil import Process, Popen
16
```
17
{ .api }
18
19
## Basic Usage
20
21
```python
22
import psutil
23
24
# System info
25
print(f"CPU count: {psutil.cpu_count()}")
26
print(f"Memory: {psutil.virtual_memory()}")
27
print(f"Boot time: {psutil.boot_time()}")
28
29
# Process info
30
p = psutil.Process() # Current process
31
print(f"PID: {p.pid}")
32
print(f"Name: {p.name()}")
33
print(f"CPU percent: {p.cpu_percent()}")
34
35
# List all processes
36
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
37
print(proc.info)
38
```
39
{ .api }
40
41
## Architecture
42
43
psutil provides two main API categories:
44
45
### Process Class
46
The `Process` class represents individual system processes and provides comprehensive process management and monitoring capabilities. Processes can be accessed by PID or iterated over.
47
48
### System Functions
49
Module-level functions provide system-wide information about CPU, memory, disk, network, and sensors.
50
51
## Core Capabilities
52
53
### Process Management
54
- **Process Information**: Get detailed process metadata including PID, name, status, parent/children relationships
55
- **Resource Monitoring**: Monitor CPU usage, memory consumption, I/O statistics, and file handles
56
- **Process Control**: Suspend, resume, terminate, and kill processes with proper signal handling
57
- **Platform Features**: Access platform-specific attributes like ionice, rlimit, and process priorities
58
59
See: [Process Documentation](process.md)
60
61
### System Information
62
- **CPU Monitoring**: CPU count, usage statistics, frequency, and load averages
63
- **Memory Stats**: Virtual memory, swap usage, and memory mapping information
64
- **Disk Operations**: Disk usage, partitions, and I/O counters for storage devices
65
- **Network Stats**: Network interface information, connections, and I/O statistics
66
67
See: [System Information Documentation](system-info.md)
68
69
### Hardware Sensors
70
- **Temperature Monitoring**: CPU and system component temperatures
71
- **Fan Control**: Fan speed monitoring across hardware components
72
- **Battery Information**: Battery status, charge level, and power management
73
74
See: [Sensors Documentation](sensors.md)
75
76
### Constants and Exceptions
77
- **Platform Constants**: Operating system and platform identification
78
- **Status Constants**: Process and connection states and statuses
79
- **Exception Handling**: Comprehensive exception hierarchy for error management
80
81
See: [Constants](constants.md) | [Exceptions](exceptions.md)
82
83
## Key API Examples
84
85
### Process Iteration
86
```python
87
# Iterate over all processes with specific attributes
88
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
89
try:
90
print(f"{proc.info['pid']}: {proc.info['name']} ({proc.info['cpu_percent']}%)")
91
except (psutil.NoSuchProcess, psutil.AccessDenied):
92
pass
93
```
94
{ .api }
95
96
### System Monitoring
97
```python
98
# Get system-wide CPU and memory usage
99
cpu_percent = psutil.cpu_percent(interval=1)
100
cpu_times_percent = psutil.cpu_times_percent(interval=1) # Detailed CPU time breakdown
101
memory = psutil.virtual_memory()
102
print(f"CPU: {cpu_percent}%, Memory: {memory.percent}%")
103
print(f"CPU User: {cpu_times_percent.user}%, System: {cpu_times_percent.system}%")
104
```
105
{ .api }
106
107
### Process Control
108
```python
109
# Find and terminate processes by name
110
for proc in psutil.process_iter(['pid', 'name']):
111
if 'python' in proc.info['name']:
112
proc.terminate() # or proc.kill() for force
113
```
114
{ .api }
115
116
## Error Handling
117
118
```python
119
try:
120
p = psutil.Process(1234)
121
print(p.name())
122
except psutil.NoSuchProcess:
123
print("Process not found")
124
except psutil.AccessDenied:
125
print("Permission denied")
126
except psutil.ZombieProcess:
127
print("Process is zombie")
128
```
129
{ .api }
130
131
### System Overview and Testing
132
133
```python
134
# Quick system overview (similar to ps/top command)
135
psutil.test() # Prints comprehensive system information to stdout
136
137
# Version information
138
print(f"psutil version: {psutil.__version__}")
139
140
# Platform-specific features
141
if psutil.WINDOWS:
142
# Windows service management
143
for service in psutil.win_service_iter():
144
if service.status() == 'running':
145
print(f"Running service: {service.name()} - {service.display_name()}")
146
147
elif psutil.LINUX:
148
# Linux-specific resource limits
149
p = psutil.Process()
150
if hasattr(psutil, 'RLIMIT_NOFILE'):
151
soft, hard = p.rlimit(psutil.RLIMIT_NOFILE)
152
print(f"File descriptor limits: soft={soft}, hard={hard}")
153
```
154
{ .api }
155
156
## Platform Compatibility
157
158
psutil provides cross-platform APIs with consistent interfaces. Some features may have platform-specific availability or behavior differences. Platform-specific features are clearly documented in the respective sections.
159
160
Supported platforms: Linux, Windows, macOS, FreeBSD, OpenBSD, NetBSD, AIX, Solaris