or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

constants.mdexceptions.mdindex.mdprocess.mdsensors.mdsystem-info.md

system-info.mddocs/

0

# System Information

1

2

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.

3

4

## CPU Information and Monitoring

5

6

### CPU Count and Topology

7

8

```python

9

import psutil

10

11

# CPU count

12

logical_cpus = psutil.cpu_count() # Logical CPUs (including hyperthreading)

13

physical_cpus = psutil.cpu_count(logical=False) # Physical CPU cores only

14

15

# CPU frequency (if supported)

16

if hasattr(psutil, 'cpu_freq'):

17

freq = psutil.cpu_freq() # Current, min, max frequency

18

per_cpu_freq = psutil.cpu_freq(percpu=True) # Per-CPU frequency info

19

```

20

{ .api }

21

22

### CPU Usage Statistics

23

24

```python

25

# CPU usage percentage

26

cpu_percent = psutil.cpu_percent() # Overall CPU usage

27

cpu_percent_interval = psutil.cpu_percent(interval=1) # With measurement interval

28

per_cpu_percent = psutil.cpu_percent(percpu=True) # Per-CPU usage

29

30

# CPU times

31

cpu_times = psutil.cpu_times() # Overall CPU times

32

per_cpu_times = psutil.cpu_times(percpu=True) # Per-CPU times

33

34

# CPU statistics

35

cpu_stats = psutil.cpu_stats() # Context switches, interrupts, soft interrupts

36

37

# CPU time percentages (detailed breakdown)

38

cpu_times_percent = psutil.cpu_times_percent() # Overall CPU time percentages

39

cpu_times_percent_interval = psutil.cpu_times_percent(interval=1) # With measurement interval

40

per_cpu_times_percent = psutil.cpu_times_percent(percpu=True) # Per-CPU time percentages

41

```

42

{ .api }

43

44

### Load Average (Unix)

45

46

```python

47

# System load average (Unix platforms with getloadavg support)

48

if hasattr(psutil, 'getloadavg'):

49

load1, load5, load15 = psutil.getloadavg()

50

print(f"Load average: {load1:.2f}, {load5:.2f}, {load15:.2f}")

51

else:

52

print("Load average not available on this platform")

53

```

54

{ .api }

55

56

## Memory Information

57

58

### Virtual Memory

59

60

```python

61

# System memory usage

62

memory = psutil.virtual_memory()

63

64

print(f"Total: {memory.total / 1024**3:.2f} GB")

65

print(f"Available: {memory.available / 1024**3:.2f} GB")

66

print(f"Used: {memory.used / 1024**3:.2f} GB")

67

print(f"Percentage: {memory.percent}%")

68

print(f"Free: {memory.free / 1024**3:.2f} GB")

69

70

# Additional memory fields (platform-specific)

71

if hasattr(memory, 'buffers'):

72

print(f"Buffers: {memory.buffers / 1024**3:.2f} GB")

73

if hasattr(memory, 'cached'):

74

print(f"Cached: {memory.cached / 1024**3:.2f} GB")

75

```

76

{ .api }

77

78

### Swap Memory

79

80

```python

81

# Swap memory information

82

swap = psutil.swap_memory()

83

84

print(f"Swap Total: {swap.total / 1024**3:.2f} GB")

85

print(f"Swap Used: {swap.used / 1024**3:.2f} GB")

86

print(f"Swap Free: {swap.free / 1024**3:.2f} GB")

87

print(f"Swap Percentage: {swap.percent}%")

88

print(f"Swap In: {swap.sin}") # Bytes swapped in

89

print(f"Swap Out: {swap.sout}") # Bytes swapped out

90

```

91

{ .api }

92

93

## Disk Information

94

95

### Disk Usage

96

97

```python

98

# Disk usage for specific path

99

usage = psutil.disk_usage('/') # Unix root

100

# usage = psutil.disk_usage('C:\\') # Windows C: drive

101

102

print(f"Total: {usage.total / 1024**3:.2f} GB")

103

print(f"Used: {usage.used / 1024**3:.2f} GB")

104

print(f"Free: {usage.free / 1024**3:.2f} GB")

105

print(f"Percentage: {(usage.used / usage.total) * 100:.1f}%")

106

```

107

{ .api }

108

109

### Disk Partitions

110

111

```python

112

# List all disk partitions

113

partitions = psutil.disk_partitions()

114

115

for partition in partitions:

116

print(f"Device: {partition.device}")

117

print(f"Mountpoint: {partition.mountpoint}")

118

print(f"Filesystem: {partition.fstype}")

119

print(f"Options: {partition.opts}")

120

121

# Get usage for each partition

122

try:

123

usage = psutil.disk_usage(partition.mountpoint)

124

print(f" Total: {usage.total / 1024**3:.2f} GB")

125

print(f" Used: {usage.used / 1024**3:.2f} GB")

126

print(f" Free: {usage.free / 1024**3:.2f} GB")

127

except PermissionError:

128

print(" Permission denied")

129

```

130

{ .api }

131

132

### Disk I/O Statistics

133

134

```python

135

# System-wide disk I/O

136

disk_io = psutil.disk_io_counters()

137

if disk_io:

138

print(f"Read bytes: {disk_io.read_bytes}")

139

print(f"Write bytes: {disk_io.write_bytes}")

140

print(f"Read count: {disk_io.read_count}")

141

print(f"Write count: {disk_io.write_count}")

142

print(f"Read time: {disk_io.read_time} ms")

143

print(f"Write time: {disk_io.write_time} ms")

144

145

# Per-disk I/O statistics

146

per_disk_io = psutil.disk_io_counters(perdisk=True)

147

for device, io in per_disk_io.items():

148

print(f"{device}: R={io.read_bytes} W={io.write_bytes}")

149

```

150

{ .api }

151

152

## Network Information

153

154

### Network I/O Statistics

155

156

```python

157

# System-wide network I/O

158

net_io = psutil.net_io_counters()

159

print(f"Bytes sent: {net_io.bytes_sent}")

160

print(f"Bytes received: {net_io.bytes_recv}")

161

print(f"Packets sent: {net_io.packets_sent}")

162

print(f"Packets received: {net_io.packets_recv}")

163

164

# Per-interface network I/O

165

per_nic_io = psutil.net_io_counters(pernic=True)

166

for interface, io in per_nic_io.items():

167

print(f"{interface}: TX={io.bytes_sent} RX={io.bytes_recv}")

168

```

169

{ .api }

170

171

### Network Interfaces

172

173

```python

174

# Network interface addresses

175

addrs = psutil.net_if_addrs()

176

for interface, addr_list in addrs.items():

177

print(f"Interface: {interface}")

178

for addr in addr_list:

179

print(f" Family: {addr.family}")

180

print(f" Address: {addr.address}")

181

if addr.netmask:

182

print(f" Netmask: {addr.netmask}")

183

if addr.broadcast:

184

print(f" Broadcast: {addr.broadcast}")

185

186

# Network interface statistics

187

stats = psutil.net_if_stats()

188

for interface, stat in stats.items():

189

print(f"{interface}: Up={stat.isup}, Speed={stat.speed}Mb/s, MTU={stat.mtu}")

190

```

191

{ .api }

192

193

### Network Connections

194

195

```python

196

# System-wide network connections

197

connections = psutil.net_connections()

198

for conn in connections[:5]: # Show first 5

199

print(f"Protocol: {conn.type}")

200

print(f"Local: {conn.laddr}")

201

print(f"Remote: {conn.raddr}")

202

print(f"Status: {conn.status}")

203

print(f"PID: {conn.pid}")

204

205

# Filter by connection type

206

tcp_connections = psutil.net_connections(kind='tcp')

207

udp_connections = psutil.net_connections(kind='udp')

208

inet_connections = psutil.net_connections(kind='inet') # TCP + UDP

209

```

210

{ .api }

211

212

## System Information

213

214

### Boot Time and Uptime

215

216

```python

217

import datetime

218

219

# System boot time

220

boot_timestamp = psutil.boot_time()

221

boot_time = datetime.datetime.fromtimestamp(boot_timestamp)

222

print(f"Boot time: {boot_time}")

223

224

# System uptime

225

uptime_seconds = psutil.time.time() - boot_timestamp

226

uptime_string = str(datetime.timedelta(seconds=uptime_seconds))

227

print(f"Uptime: {uptime_string}")

228

```

229

{ .api }

230

231

### Users

232

233

```python

234

# Currently logged in users

235

users = psutil.users()

236

for user in users:

237

print(f"User: {user.name}")

238

print(f"Terminal: {user.terminal}")

239

print(f"Host: {user.host}")

240

print(f"Started: {datetime.datetime.fromtimestamp(user.started)}")

241

```

242

{ .api }

243

244

## System Monitoring Examples

245

246

### Complete System Overview

247

248

```python

249

def system_overview():

250

"""Get comprehensive system information."""

251

info = {}

252

253

# CPU

254

info['cpu'] = {

255

'count_logical': psutil.cpu_count(),

256

'count_physical': psutil.cpu_count(logical=False),

257

'usage_percent': psutil.cpu_percent(interval=1),

258

'frequency': psutil.cpu_freq()._asdict() if hasattr(psutil, 'cpu_freq') and psutil.cpu_freq() else None

259

}

260

261

# Memory

262

memory = psutil.virtual_memory()

263

swap = psutil.swap_memory()

264

info['memory'] = {

265

'virtual': memory._asdict(),

266

'swap': swap._asdict()

267

}

268

269

# Disk

270

info['disk'] = {}

271

for partition in psutil.disk_partitions():

272

try:

273

usage = psutil.disk_usage(partition.mountpoint)

274

info['disk'][partition.device] = {

275

'mountpoint': partition.mountpoint,

276

'fstype': partition.fstype,

277

'usage': usage._asdict()

278

}

279

except PermissionError:

280

pass

281

282

# Network

283

net_io = psutil.net_io_counters()

284

info['network'] = {

285

'io': net_io._asdict() if net_io else None,

286

'interfaces': list(psutil.net_if_addrs().keys())

287

}

288

289

# System

290

info['system'] = {

291

'boot_time': psutil.boot_time(),

292

'users': len(psutil.users())

293

}

294

295

return info

296

297

# Get system overview

298

overview = system_overview()

299

```

300

{ .api }

301

302

### Resource Monitoring Loop

303

304

```python

305

import time

306

307

def monitor_system(duration=60, interval=5):

308

"""Monitor system resources for specified duration."""

309

start_time = time.time()

310

311

print(f"{'Time':<8} {'CPU%':<6} {'Memory%':<8} {'Disk R/s':<10} {'Disk W/s':<10} {'Net RX':<10} {'Net TX':<10}")

312

print("-" * 70)

313

314

# Get initial values for rate calculations

315

prev_disk = psutil.disk_io_counters()

316

prev_net = psutil.net_io_counters()

317

prev_time = time.time()

318

319

while time.time() - start_time < duration:

320

# Current measurements

321

cpu_percent = psutil.cpu_percent(interval=1)

322

memory_percent = psutil.virtual_memory().percent

323

324

curr_disk = psutil.disk_io_counters()

325

curr_net = psutil.net_io_counters()

326

curr_time = time.time()

327

328

# Calculate rates

329

time_delta = curr_time - prev_time

330

if prev_disk and curr_disk and time_delta > 0:

331

disk_read_rate = (curr_disk.read_bytes - prev_disk.read_bytes) / time_delta

332

disk_write_rate = (curr_disk.write_bytes - prev_disk.write_bytes) / time_delta

333

else:

334

disk_read_rate = disk_write_rate = 0

335

336

if prev_net and curr_net and time_delta > 0:

337

net_recv_rate = (curr_net.bytes_recv - prev_net.bytes_recv) / time_delta

338

net_sent_rate = (curr_net.bytes_sent - prev_net.bytes_sent) / time_delta

339

else:

340

net_recv_rate = net_sent_rate = 0

341

342

# Display

343

timestamp = time.strftime("%H:%M:%S")

344

print(f"{timestamp:<8} {cpu_percent:<6.1f} {memory_percent:<8.1f} "

345

f"{disk_read_rate/1024:<10.0f} {disk_write_rate/1024:<10.0f} "

346

f"{net_recv_rate/1024:<10.0f} {net_sent_rate/1024:<10.0f}")

347

348

# Update previous values

349

prev_disk, prev_net, prev_time = curr_disk, curr_net, curr_time

350

351

time.sleep(interval)

352

353

# Monitor system for 5 minutes

354

# monitor_system(duration=300, interval=5)

355

```

356

{ .api }

357

358

## Utility and Debugging Functions

359

360

### Test and Debugging

361

362

```python

363

# Test function - displays system information in ps-like format

364

psutil.test() # Prints comprehensive system/process overview to stdout

365

366

# Version information

367

print(f"psutil version: {psutil.__version__}")

368

print(f"Version info tuple: {psutil.version_info}")

369

370

# Debug mode (for development/troubleshooting)

371

psutil._set_debug(True) # Enable debug output to stderr

372

psutil._set_debug(False) # Disable debug output

373

```

374

{ .api }

375

376

## Platform-Specific Features

377

378

### Linux-Specific

379

380

```python

381

if psutil.LINUX:

382

# Additional Linux-specific system info

383

try:

384

# CPU stats include more detailed info on Linux

385

cpu_stats = psutil.cpu_stats()

386

print(f"Context switches: {cpu_stats.ctx_switches}")

387

print(f"Interrupts: {cpu_stats.interrupts}")

388

print(f"Soft interrupts: {cpu_stats.soft_interrupts}")

389

print(f"System calls: {cpu_stats.syscalls}")

390

except AttributeError:

391

pass

392

```

393

{ .api }

394

395

### Windows-Specific

396

397

```python

398

if psutil.WINDOWS:

399

# Windows Services Management

400

401

# List all Windows services

402

for service in psutil.win_service_iter():

403

print(f"Service: {service.name()}")

404

print(f"Display name: {service.display_name()}")

405

print(f"Status: {service.status()}")

406

407

# Get specific service by name

408

try:

409

service = psutil.win_service_get('wuauserv') # Windows Update service

410

print(f"Service info: {service.as_dict()}")

411

print(f"Status: {service.status()}")

412

print(f"Start type: {service.start_type()}")

413

print(f"Username: {service.username()}")

414

except psutil.NoSuchProcess:

415

print("Service not found")

416

```

417

{ .api }

418

419

## Performance Considerations

420

421

- Use `interval` parameters with CPU monitoring functions for accurate measurements

422

- Cache frequently accessed system information when possible

423

- Be aware that some operations may require elevated privileges

424

- Consider platform differences when using system-specific features

425

- Network connection enumeration can be expensive on systems with many connections

426

427

## Related Documentation

428

429

- [Process Management](process.md) - Process-specific monitoring and control

430

- [Sensors](sensors.md) - Hardware sensor monitoring

431

- [Constants](constants.md) - System constants and platform identifiers

432

- [Exceptions](exceptions.md) - Exception handling for system operations