0
# Process Class
1
2
The `Process` class is the core component of psutil for process management and monitoring. It represents individual system processes and provides comprehensive access to process information, resource usage, and control operations.
3
4
## Process Creation and Access
5
6
### Creating Process Objects
7
8
```python
9
import psutil
10
11
# Current process
12
current = psutil.Process()
13
14
# Process by PID
15
p = psutil.Process(1234)
16
17
# Process using Popen (subprocess alternative)
18
p = psutil.Popen(['python', 'script.py'])
19
```
20
{ .api }
21
22
### Process Iteration
23
24
```python
25
# Iterate over all processes
26
for proc in psutil.process_iter():
27
print(proc.pid, proc.name())
28
29
# Iterate with specific attributes (more efficient)
30
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
31
print(proc.info)
32
33
# Process filtering
34
python_procs = [p for p in psutil.process_iter() if 'python' in p.name().lower()]
35
```
36
{ .api }
37
38
## Process Information Methods
39
40
### Basic Information
41
42
```python
43
p = psutil.Process()
44
45
# Process identification
46
pid = p.pid # Process ID
47
ppid = p.ppid() # Parent process ID
48
name = p.name() # Process name
49
exe = p.exe() # Executable path
50
cmdline = p.cmdline() # Command line arguments
51
environ = p.environ() # Environment variables
52
```
53
{ .api }
54
55
### Process Status and State
56
57
```python
58
# Process status
59
status = p.status() # Process status (running, sleeping, etc.)
60
is_running = p.is_running() # Check if process is running
61
create_time = p.create_time() # Process creation time
62
63
# Process relationships
64
parent = p.parent() # Parent process object
65
children = p.children() # List of child processes
66
children_recursive = p.children(recursive=True) # Include grandchildren
67
```
68
{ .api }
69
70
### User and Group Information
71
72
```python
73
# User information
74
username = p.username() # Process owner username
75
uids = p.uids() # Real, effective, saved user IDs
76
gids = p.gids() # Real, effective, saved group IDs
77
terminal = p.terminal() # Controlling terminal
78
```
79
{ .api }
80
81
## Resource Usage Methods
82
83
### CPU Monitoring
84
85
```python
86
# CPU usage
87
cpu_percent = p.cpu_percent() # CPU usage percentage
88
cpu_percent_interval = p.cpu_percent(interval=1) # With measurement interval
89
cpu_times = p.cpu_times() # CPU times (user, system)
90
cpu_affinity = p.cpu_affinity() # CPU affinity mask
91
cpu_num = p.cpu_num() # Current CPU number
92
```
93
{ .api }
94
95
### Memory Information
96
97
```python
98
# Memory usage
99
memory_info = p.memory_info() # RSS, VMS memory
100
memory_full_info = p.memory_full_info() # Extended memory info
101
memory_percent = p.memory_percent() # Memory usage percentage
102
103
# Memory mappings (Linux, FreeBSD, macOS)
104
if hasattr(p._proc, 'memory_maps'):
105
memory_maps = p.memory_maps() # Memory regions (grouped by default)
106
memory_maps_detailed = p.memory_maps(grouped=False) # Individual regions
107
```
108
{ .api }
109
110
### I/O Statistics
111
112
```python
113
# I/O operations
114
io_counters = p.io_counters() # Read/write bytes and operations
115
num_ctx_switches = p.num_ctx_switches() # Context switches
116
num_fds = p.num_fds() # Number of file descriptors (Unix)
117
num_handles = p.num_handles() # Number of handles (Windows)
118
num_threads = p.num_threads() # Number of threads
119
120
# Thread details (platform-dependent availability)
121
if hasattr(p._proc, 'threads'):
122
threads = p.threads() # List of thread info namedtuples
123
```
124
{ .api }
125
126
### File and Connection Information
127
128
```python
129
# Open files and connections
130
open_files = p.open_files() # List of open files
131
connections = p.connections() # Network connections
132
connections_all = p.connections(kind='all') # All connection types
133
```
134
{ .api }
135
136
### Thread Information
137
138
```python
139
# Thread details (Linux, Windows, FreeBSD, macOS)
140
if hasattr(psutil.Process().__class__, 'threads'):
141
threads = p.threads() # Returns list of thread namedtuples
142
for thread in threads:
143
print(f"Thread ID: {thread.id}")
144
print(f"User time: {thread.user_time}")
145
print(f"System time: {thread.system_time}")
146
```
147
{ .api }
148
149
## Process Control Methods
150
151
### Process Lifecycle
152
153
```python
154
# Process control
155
p.suspend() # Suspend process
156
p.resume() # Resume suspended process
157
p.terminate() # Terminate process (SIGTERM)
158
p.kill() # Kill process (SIGKILL)
159
160
# Wait for process termination
161
p.wait() # Wait indefinitely
162
p.wait(timeout=10) # Wait with timeout
163
```
164
{ .api }
165
166
### Signal Handling
167
168
```python
169
# Send signals (Unix)
170
import signal
171
p.send_signal(signal.SIGTERM) # Send specific signal
172
p.send_signal(signal.SIGUSR1) # Send custom signal
173
```
174
{ .api }
175
176
## Platform-Specific Methods
177
178
### Linux-Specific
179
180
```python
181
# Linux only
182
if psutil.LINUX:
183
rlimit = p.rlimit(psutil.RLIMIT_NOFILE) # Resource limits
184
ionice = p.ionice() # I/O priority
185
cwd = p.cwd() # Current working directory
186
root = p.rlimit(psutil.RLIMIT_CORE) # Core dump size limit
187
```
188
{ .api }
189
190
### Windows-Specific
191
192
```python
193
# Windows only
194
if psutil.WINDOWS:
195
nice = p.nice() # Process priority
196
ionice = p.ionice() # I/O priority class
197
num_handles = p.num_handles() # Windows handles
198
```
199
{ .api }
200
201
### macOS-Specific
202
203
```python
204
# macOS only
205
if psutil.OSX:
206
nice = p.nice() # Process priority (nice value)
207
# Additional macOS-specific attributes available
208
```
209
{ .api }
210
211
## Advanced Process Operations
212
213
### Process Comparison and Hashing
214
215
```python
216
p1 = psutil.Process(1234)
217
p2 = psutil.Process(1234)
218
219
# Process equality
220
equal = (p1 == p2) # True if same PID
221
same_process = p1.is_running() and p2.is_running()
222
223
# Process hashing
224
process_set = {p1, p2} # Can use in sets/dicts
225
```
226
{ .api }
227
228
### Process Attributes Access
229
230
```python
231
# Access multiple attributes efficiently
232
attrs = p.as_dict(['pid', 'name', 'cpu_percent', 'memory_info'])
233
print(attrs)
234
235
# With error handling for individual attributes
236
attrs = p.as_dict(['pid', 'name'], ad_value='N/A') # Use default for access denied
237
```
238
{ .api }
239
240
### Process Tree Operations
241
242
```python
243
def print_process_tree(parent, indent=0):
244
"""Print process tree starting from parent."""
245
try:
246
print(' ' * indent + f"{parent.pid} {parent.name()}")
247
for child in parent.children():
248
print_process_tree(child, indent + 2)
249
except (psutil.NoSuchProcess, psutil.AccessDenied):
250
pass
251
252
# Print tree for process and all children
253
print_process_tree(psutil.Process())
254
```
255
{ .api }
256
257
### Performance Optimization with oneshot()
258
259
```python
260
# Use oneshot() context manager for efficient multiple attribute access
261
p = psutil.Process()
262
263
# Without oneshot - each call makes separate system calls
264
name = p.name()
265
cpu_percent = p.cpu_percent()
266
memory_info = p.memory_info()
267
create_time = p.create_time()
268
269
# With oneshot - single system call fetches multiple attributes
270
with p.oneshot():
271
name = p.name() # Fetches and caches multiple attributes
272
cpu_percent = p.cpu_percent() # Returns cached value
273
memory_info = p.memory_info() # Returns cached value
274
create_time = p.create_time() # Returns cached value
275
276
# Especially beneficial for process monitoring loops
277
def monitor_processes():
278
"""Efficiently monitor multiple processes."""
279
for proc in psutil.process_iter():
280
try:
281
with proc.oneshot():
282
# All these calls use cached data from single syscall
283
info = {
284
'pid': proc.pid,
285
'name': proc.name(),
286
'cpu_percent': proc.cpu_percent(),
287
'memory_rss': proc.memory_info().rss,
288
'status': proc.status(),
289
'create_time': proc.create_time()
290
}
291
print(info)
292
except (psutil.NoSuchProcess, psutil.AccessDenied):
293
pass
294
```
295
{ .api }
296
297
## Exception Handling
298
299
```python
300
try:
301
p = psutil.Process(1234)
302
print(f"Process: {p.name()}")
303
print(f"CPU: {p.cpu_percent()}")
304
print(f"Memory: {p.memory_info()}")
305
306
except psutil.NoSuchProcess:
307
print("Process not found or terminated")
308
except psutil.AccessDenied:
309
print("Permission denied - may need elevated privileges")
310
except psutil.ZombieProcess:
311
print("Process exists but is zombie state")
312
except psutil.TimeoutExpired:
313
print("Operation timed out")
314
```
315
{ .api }
316
317
## Process Monitoring Patterns
318
319
### Resource Monitoring Loop
320
321
```python
322
import time
323
324
def monitor_process(pid, duration=60):
325
"""Monitor process for specified duration."""
326
try:
327
p = psutil.Process(pid)
328
start_time = time.time()
329
330
while time.time() - start_time < duration:
331
if not p.is_running():
332
print("Process terminated")
333
break
334
335
cpu = p.cpu_percent(interval=1)
336
memory = p.memory_info()
337
338
print(f"CPU: {cpu:5.1f}% | Memory: {memory.rss / 1024**2:6.1f} MB")
339
340
except psutil.NoSuchProcess:
341
print("Process not found")
342
```
343
{ .api }
344
345
### Process Statistics Collection
346
347
```python
348
def get_process_stats(proc):
349
"""Get comprehensive process statistics."""
350
try:
351
return {
352
'pid': proc.pid,
353
'name': proc.name(),
354
'status': proc.status(),
355
'cpu_percent': proc.cpu_percent(),
356
'memory_rss': proc.memory_info().rss,
357
'memory_vms': proc.memory_info().vms,
358
'num_threads': proc.num_threads(),
359
'create_time': proc.create_time(),
360
'username': proc.username()
361
}
362
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
363
return {'error': str(e)}
364
365
# Collect stats for all processes
366
all_stats = []
367
for proc in psutil.process_iter():
368
stats = get_process_stats(proc)
369
if 'error' not in stats:
370
all_stats.append(stats)
371
```
372
{ .api }
373
374
## Performance Considerations
375
376
- Use `process_iter()` with attribute lists for efficient bulk operations
377
- Cache Process objects when monitoring the same process repeatedly
378
- Handle exceptions appropriately as processes can terminate between calls
379
- Use `interval` parameter with `cpu_percent()` for accurate measurements
380
- Consider platform differences when using platform-specific methods
381
382
## Related Documentation
383
384
- [System Information](system-info.md) - System-wide monitoring functions
385
- [Constants](constants.md) - Process status constants and platform identifiers
386
- [Exceptions](exceptions.md) - Complete exception hierarchy and handling