or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

constants.mddocs/

0

# Constants and Enumerations

1

2

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.

3

4

## Platform Constants

5

6

### Platform Identification

7

8

```python

9

import psutil

10

11

# Platform detection constants

12

print(f"Linux: {psutil.LINUX}") # True on Linux

13

print(f"Windows: {psutil.WINDOWS}") # True on Windows

14

print(f"macOS: {psutil.OSX}") # True on macOS

15

print(f"FreeBSD: {psutil.FREEBSD}") # True on FreeBSD

16

print(f"OpenBSD: {psutil.OPENBSD}") # True on OpenBSD

17

print(f"NetBSD: {psutil.NETBSD}") # True on NetBSD

18

print(f"Sun OS: {psutil.SUNOS}") # True on Solaris/SunOS

19

print(f"AIX: {psutil.AIX}") # True on AIX

20

21

# Platform-specific code

22

if psutil.LINUX:

23

print("Running on Linux - can use Linux-specific features")

24

elif psutil.WINDOWS:

25

print("Running on Windows - can use Windows-specific features")

26

elif psutil.OSX:

27

print("Running on macOS - can use macOS-specific features")

28

```

29

{ .api }

30

31

## Process Status Constants

32

33

### Process State Values

34

35

```python

36

# Process status constants

37

STATUS_RUNNING = psutil.STATUS_RUNNING # Process is running

38

STATUS_SLEEPING = psutil.STATUS_SLEEPING # Process is sleeping

39

STATUS_DISK_SLEEP = psutil.STATUS_DISK_SLEEP # Uninterruptible sleep (I/O)

40

STATUS_STOPPED = psutil.STATUS_STOPPED # Process is stopped

41

STATUS_TRACING_STOP = psutil.STATUS_TRACING_STOP # Tracing stop

42

STATUS_ZOMBIE = psutil.STATUS_ZOMBIE # Zombie process

43

STATUS_DEAD = psutil.STATUS_DEAD # Dead process

44

STATUS_WAKE_KILL = psutil.STATUS_WAKE_KILL # Wake kill

45

STATUS_WAKING = psutil.STATUS_WAKING # Waking up

46

STATUS_IDLE = psutil.STATUS_IDLE # Idle (macOS, FreeBSD)

47

STATUS_LOCKED = psutil.STATUS_LOCKED # Locked (FreeBSD)

48

STATUS_WAITING = psutil.STATUS_WAITING # Waiting (FreeBSD)

49

STATUS_SUSPENDED = psutil.STATUS_SUSPENDED # Suspended (NetBSD)

50

STATUS_PARKED = psutil.STATUS_PARKED # Parked (Linux)

51

52

# Usage example

53

def get_process_status_name(status):

54

"""Get human-readable process status name."""

55

status_names = {

56

psutil.STATUS_RUNNING: "Running",

57

psutil.STATUS_SLEEPING: "Sleeping",

58

psutil.STATUS_DISK_SLEEP: "Disk Sleep",

59

psutil.STATUS_STOPPED: "Stopped",

60

psutil.STATUS_ZOMBIE: "Zombie",

61

psutil.STATUS_DEAD: "Dead",

62

psutil.STATUS_IDLE: "Idle"

63

}

64

return status_names.get(status, f"Unknown ({status})")

65

66

# Check process status

67

for proc in psutil.process_iter(['pid', 'name']):

68

try:

69

status = proc.status()

70

status_name = get_process_status_name(status)

71

print(f"PID {proc.pid}: {proc.name()} - {status_name}")

72

except (psutil.NoSuchProcess, psutil.AccessDenied):

73

pass

74

```

75

{ .api }

76

77

## Connection Constants

78

79

### Connection Types

80

81

```python

82

# Address family constants (socket families)

83

AF_LINK = psutil.AF_LINK # Link layer (macOS, FreeBSD)

84

85

# Connection status constants

86

CONN_ESTABLISHED = psutil.CONN_ESTABLISHED # Connection established

87

CONN_SYN_SENT = psutil.CONN_SYN_SENT # SYN sent

88

CONN_SYN_RECV = psutil.CONN_SYN_RECV # SYN received

89

CONN_FIN_WAIT1 = psutil.CONN_FIN_WAIT1 # FIN wait 1

90

CONN_FIN_WAIT2 = psutil.CONN_FIN_WAIT2 # FIN wait 2

91

CONN_TIME_WAIT = psutil.CONN_TIME_WAIT # Time wait

92

CONN_CLOSE = psutil.CONN_CLOSE # Closed

93

CONN_CLOSE_WAIT = psutil.CONN_CLOSE_WAIT # Close wait

94

CONN_LAST_ACK = psutil.CONN_LAST_ACK # Last ACK

95

CONN_LISTEN = psutil.CONN_LISTEN # Listening

96

CONN_CLOSING = psutil.CONN_CLOSING # Closing

97

CONN_NONE = psutil.CONN_NONE # No status

98

99

# Usage example

100

def analyze_connections():

101

"""Analyze network connections by status."""

102

status_count = {}

103

104

for conn in psutil.net_connections():

105

status = conn.status

106

status_count[status] = status_count.get(status, 0) + 1

107

108

print("Connection status summary:")

109

for status, count in status_count.items():

110

print(f" {status}: {count}")

111

112

# analyze_connections()

113

```

114

{ .api }

115

116

### Network Interface Constants

117

118

```python

119

# Network interface duplex constants

120

NIC_DUPLEX_FULL = psutil.NIC_DUPLEX_FULL # Full duplex

121

NIC_DUPLEX_HALF = psutil.NIC_DUPLEX_HALF # Half duplex

122

NIC_DUPLEX_UNKNOWN = psutil.NIC_DUPLEX_UNKNOWN # Unknown duplex

123

124

# Usage example

125

def check_interface_duplex():

126

"""Check network interface duplex settings."""

127

stats = psutil.net_if_stats()

128

129

for interface, stat in stats.items():

130

if hasattr(stat, 'duplex'):

131

duplex_name = {

132

psutil.NIC_DUPLEX_FULL: "Full",

133

psutil.NIC_DUPLEX_HALF: "Half",

134

psutil.NIC_DUPLEX_UNKNOWN: "Unknown"

135

}.get(stat.duplex, "N/A")

136

137

print(f"{interface}: {duplex_name} duplex")

138

139

# check_interface_duplex()

140

```

141

{ .api }

142

143

## Power Management Constants

144

145

### Battery and Power Constants

146

147

```python

148

# Power time constants

149

POWER_TIME_UNKNOWN = psutil.POWER_TIME_UNKNOWN # Unknown time remaining

150

POWER_TIME_UNLIMITED = psutil.POWER_TIME_UNLIMITED # Unlimited (plugged in)

151

152

# Usage example

153

def format_battery_time(seconds):

154

"""Format battery time with proper handling of special values."""

155

if seconds == psutil.POWER_TIME_UNKNOWN:

156

return "Unknown"

157

elif seconds == psutil.POWER_TIME_UNLIMITED:

158

return "Unlimited (plugged in)"

159

else:

160

hours, remainder = divmod(seconds, 3600)

161

minutes, _ = divmod(remainder, 60)

162

return f"{hours}h {minutes}m"

163

164

# Check battery status

165

try:

166

battery = psutil.sensors_battery()

167

if battery:

168

time_str = format_battery_time(battery.secsleft)

169

print(f"Battery: {battery.percent}%, Time remaining: {time_str}")

170

except AttributeError:

171

print("Battery information not available")

172

```

173

{ .api }

174

175

## Linux-Specific Constants

176

177

### I/O Priority Constants (Linux)

178

179

```python

180

if psutil.LINUX:

181

# I/O scheduling class constants (Linux only)

182

IOPRIO_CLASS_NONE = psutil.IOPRIO_CLASS_NONE # No specific I/O class

183

IOPRIO_CLASS_RT = psutil.IOPRIO_CLASS_RT # Real-time I/O class

184

IOPRIO_CLASS_BE = psutil.IOPRIO_CLASS_BE # Best-effort I/O class

185

IOPRIO_CLASS_IDLE = psutil.IOPRIO_CLASS_IDLE # Idle I/O class

186

187

# Usage example

188

def set_process_ionice(pid, ioclass, value=0):

189

"""Set process I/O priority on Linux."""

190

try:

191

p = psutil.Process(pid)

192

p.ionice(ioclass, value)

193

print(f"Set I/O priority for PID {pid}: class={ioclass}, value={value}")

194

except (psutil.NoSuchProcess, psutil.AccessDenied) as e:

195

print(f"Error setting I/O priority: {e}")

196

197

# Set current process to idle I/O class

198

# set_process_ionice(psutil.Process().pid, psutil.IOPRIO_CLASS_IDLE)

199

```

200

{ .api }

201

202

### Resource Limit Constants (Unix)

203

204

```python

205

if hasattr(psutil, 'RLIMIT_NOFILE'):

206

# Resource limit constants (Unix-like systems)

207

# Basic resource limits (available on most Unix-like systems)

208

RLIMIT_AS = psutil.RLIMIT_AS # Address space limit

209

RLIMIT_CORE = psutil.RLIMIT_CORE # Core dump size limit

210

RLIMIT_CPU = psutil.RLIMIT_CPU # CPU time limit

211

RLIMIT_DATA = psutil.RLIMIT_DATA # Data segment size limit

212

RLIMIT_FSIZE = psutil.RLIMIT_FSIZE # File size limit

213

RLIMIT_MEMLOCK = psutil.RLIMIT_MEMLOCK # Locked memory limit

214

RLIMIT_NOFILE = psutil.RLIMIT_NOFILE # Number of open files limit

215

RLIMIT_NPROC = psutil.RLIMIT_NPROC # Number of processes limit

216

RLIMIT_RSS = psutil.RLIMIT_RSS # RSS memory limit

217

RLIMIT_STACK = psutil.RLIMIT_STACK # Stack size limit

218

219

# Linux-specific resource limits

220

if hasattr(psutil, 'RLIMIT_LOCKS'):

221

RLIMIT_LOCKS = psutil.RLIMIT_LOCKS # File locks limit (Linux)

222

if hasattr(psutil, 'RLIMIT_MSGQUEUE'):

223

RLIMIT_MSGQUEUE = psutil.RLIMIT_MSGQUEUE # Message queue bytes (Linux)

224

if hasattr(psutil, 'RLIMIT_NICE'):

225

RLIMIT_NICE = psutil.RLIMIT_NICE # Nice priority limit (Linux)

226

if hasattr(psutil, 'RLIMIT_RTPRIO'):

227

RLIMIT_RTPRIO = psutil.RLIMIT_RTPRIO # Real-time priority (Linux)

228

if hasattr(psutil, 'RLIMIT_RTTIME'):

229

RLIMIT_RTTIME = psutil.RLIMIT_RTTIME # Real-time CPU time (Linux)

230

if hasattr(psutil, 'RLIMIT_SIGPENDING'):

231

RLIMIT_SIGPENDING = psutil.RLIMIT_SIGPENDING # Pending signals (Linux)

232

233

# FreeBSD-specific resource limits

234

if hasattr(psutil, 'RLIMIT_SWAP'):

235

RLIMIT_SWAP = psutil.RLIMIT_SWAP # Swap space (FreeBSD)

236

if hasattr(psutil, 'RLIMIT_SBSIZE'):

237

RLIMIT_SBSIZE = psutil.RLIMIT_SBSIZE # Socket buffer size (FreeBSD)

238

if hasattr(psutil, 'RLIMIT_NPTS'):

239

RLIMIT_NPTS = psutil.RLIMIT_NPTS # Pseudo-terminals (FreeBSD)

240

241

# RLIM_INFINITY constant

242

if hasattr(psutil, 'RLIM_INFINITY'):

243

RLIM_INFINITY = psutil.RLIM_INFINITY # Unlimited resource value

244

245

# Usage example

246

def check_resource_limits(pid=None):

247

"""Check resource limits for a process."""

248

try:

249

p = psutil.Process(pid)

250

251

limits_to_check = [

252

('NOFILE', psutil.RLIMIT_NOFILE, "Open files"),

253

('NPROC', psutil.RLIMIT_NPROC, "Processes"),

254

('STACK', psutil.RLIMIT_STACK, "Stack size"),

255

('DATA', psutil.RLIMIT_DATA, "Data segment"),

256

]

257

258

print(f"Resource limits for PID {p.pid}:")

259

for name, constant, description in limits_to_check:

260

try:

261

soft, hard = p.rlimit(constant)

262

print(f" {description}: soft={soft}, hard={hard}")

263

except (AttributeError, OSError):

264

print(f" {description}: Not available")

265

266

except psutil.NoSuchProcess:

267

print("Process not found")

268

269

# Check limits for current process

270

# check_resource_limits()

271

```

272

{ .api }

273

274

## Windows-Specific Constants

275

276

### Process Priority Constants (Windows)

277

278

```python

279

if psutil.WINDOWS:

280

# Windows process priority constants

281

try:

282

ABOVE_NORMAL_PRIORITY_CLASS = psutil.ABOVE_NORMAL_PRIORITY_CLASS

283

BELOW_NORMAL_PRIORITY_CLASS = psutil.BELOW_NORMAL_PRIORITY_CLASS

284

HIGH_PRIORITY_CLASS = psutil.HIGH_PRIORITY_CLASS

285

IDLE_PRIORITY_CLASS = psutil.IDLE_PRIORITY_CLASS

286

NORMAL_PRIORITY_CLASS = psutil.NORMAL_PRIORITY_CLASS

287

REALTIME_PRIORITY_CLASS = psutil.REALTIME_PRIORITY_CLASS

288

289

# Usage example

290

def set_windows_priority(pid, priority_class):

291

"""Set Windows process priority."""

292

try:

293

p = psutil.Process(pid)

294

p.nice(priority_class)

295

print(f"Set priority for PID {pid} to {priority_class}")

296

except (psutil.NoSuchProcess, psutil.AccessDenied) as e:

297

print(f"Error setting priority: {e}")

298

299

except AttributeError:

300

print("Windows priority constants not available")

301

302

# I/O Priority Constants

303

304

### Windows I/O Priority

305

```python

306

if psutil.WINDOWS:

307

# Windows I/O priority constants

308

try:

309

IOPRIO_VERYLOW = psutil.IOPRIO_VERYLOW # Very low I/O priority

310

IOPRIO_LOW = psutil.IOPRIO_LOW # Low I/O priority

311

IOPRIO_NORMAL = psutil.IOPRIO_NORMAL # Normal I/O priority

312

IOPRIO_HIGH = psutil.IOPRIO_HIGH # High I/O priority

313

314

# Usage example

315

def set_io_priority(pid, io_class):

316

"""Set Windows process I/O priority."""

317

try:

318

p = psutil.Process(pid)

319

p.ionice(io_class)

320

print(f"Set I/O priority for PID {pid} to {io_class}")

321

except (psutil.NoSuchProcess, psutil.AccessDenied) as e:

322

print(f"Error setting I/O priority: {e}")

323

324

except AttributeError:

325

print("Windows I/O priority constants not available")

326

```

327

{ .api }

328

329

### Linux I/O Priority

330

```python

331

if psutil.LINUX:

332

# Linux I/O scheduling class constants

333

try:

334

IOPRIO_CLASS_NONE = psutil.IOPRIO_CLASS_NONE # No specific I/O class

335

IOPRIO_CLASS_RT = psutil.IOPRIO_CLASS_RT # Real-time I/O class

336

IOPRIO_CLASS_BE = psutil.IOPRIO_CLASS_BE # Best-effort I/O class

337

IOPRIO_CLASS_IDLE = psutil.IOPRIO_CLASS_IDLE # Idle I/O class

338

339

# Usage example

340

def set_linux_io_priority(pid, io_class, value=4):

341

"""Set Linux process I/O priority."""

342

try:

343

p = psutil.Process(pid)

344

p.ionice(io_class, value) # value 0-7 for BE/RT classes

345

print(f"Set I/O class {io_class} with value {value} for PID {pid}")

346

except (psutil.NoSuchProcess, psutil.AccessDenied) as e:

347

print(f"Error setting I/O priority: {e}")

348

349

except AttributeError:

350

print("Linux I/O priority constants not available")

351

```

352

{ .api }

353

354

## Socket and Address Family Constants

355

356

### Extended Socket Types

357

358

```python

359

# Socket type constants (platform-dependent)

360

if hasattr(psutil, 'AF_LINK'):

361

AF_LINK = psutil.AF_LINK # Link layer interface (BSD, macOS)

362

363

# Usage in connection filtering

364

def filter_connections_by_family():

365

"""Filter connections by address family."""

366

connections = psutil.net_connections()

367

368

family_count = {}

369

for conn in connections:

370

family = conn.family

371

family_count[family] = family_count.get(family, 0) + 1

372

373

print("Connections by address family:")

374

for family, count in family_count.items():

375

family_name = {

376

2: "IPv4", # socket.AF_INET

377

10: "IPv6", # socket.AF_INET6 (on most systems)

378

}.get(family, f"Family {family}")

379

print(f" {family_name}: {count}")

380

381

# filter_connections_by_family()

382

```

383

{ .api }

384

385

## Constant Validation and Compatibility

386

387

### Platform Capability Detection

388

389

```python

390

def check_constant_availability():

391

"""Check which constants are available on current platform."""

392

constants_to_check = [

393

# Platform constants

394

('LINUX', 'psutil.LINUX'),

395

('WINDOWS', 'psutil.WINDOWS'),

396

('OSX', 'psutil.OSX'),

397

398

# Status constants

399

('STATUS_RUNNING', 'psutil.STATUS_RUNNING'),

400

('STATUS_ZOMBIE', 'psutil.STATUS_ZOMBIE'),

401

402

# Connection constants

403

('CONN_ESTABLISHED', 'psutil.CONN_ESTABLISHED'),

404

('CONN_LISTEN', 'psutil.CONN_LISTEN'),

405

406

# Power constants

407

('POWER_TIME_UNKNOWN', 'psutil.POWER_TIME_UNKNOWN'),

408

409

# Linux-specific

410

('IOPRIO_CLASS_IDLE', 'psutil.IOPRIO_CLASS_IDLE'),

411

('RLIMIT_NOFILE', 'psutil.RLIMIT_NOFILE'),

412

413

# Windows-specific

414

('HIGH_PRIORITY_CLASS', 'psutil.HIGH_PRIORITY_CLASS'),

415

]

416

417

print("Constant availability check:")

418

for name, attr_path in constants_to_check:

419

try:

420

# Use getattr with module path

421

parts = attr_path.split('.')

422

obj = psutil

423

for part in parts[1:]: # Skip 'psutil'

424

obj = getattr(obj, part)

425

426

print(f" {name}: Available ({obj})")

427

except AttributeError:

428

print(f" {name}: Not available")

429

430

# Check what constants are available

431

check_constant_availability()

432

```

433

{ .api }

434

435

### Cross-Platform Constant Usage

436

437

```python

438

def safe_get_process_info(pid):

439

"""Safely get process info with platform-aware constant usage."""

440

try:

441

p = psutil.Process(pid)

442

info = {

443

'pid': p.pid,

444

'name': p.name(),

445

'status': p.status()

446

}

447

448

# Add platform-specific info

449

if psutil.LINUX and hasattr(p, 'ionice'):

450

try:

451

ionice = p.ionice()

452

info['ionice_class'] = ionice.ioclass

453

info['ionice_value'] = ionice.value

454

except (AttributeError, psutil.AccessDenied):

455

pass

456

457

if psutil.WINDOWS and hasattr(p, 'nice'):

458

try:

459

info['priority'] = p.nice()

460

except psutil.AccessDenied:

461

pass

462

463

return info

464

465

except psutil.NoSuchProcess:

466

return None

467

468

# Get process info safely across platforms

469

info = safe_get_process_info(psutil.Process().pid)

470

if info:

471

print("Process info:", info)

472

```

473

{ .api }

474

475

## Usage Patterns

476

477

### Constant-Based Conditional Logic

478

479

```python

480

def get_system_capabilities():

481

"""Determine system capabilities based on available constants."""

482

capabilities = {

483

'platform': None,

484

'process_priority': False,

485

'io_priority': False,

486

'resource_limits': False,

487

'battery_info': False,

488

'sensors': False

489

}

490

491

# Detect platform

492

if psutil.LINUX:

493

capabilities['platform'] = 'Linux'

494

capabilities['io_priority'] = hasattr(psutil, 'IOPRIO_CLASS_IDLE')

495

capabilities['resource_limits'] = hasattr(psutil, 'RLIMIT_NOFILE')

496

elif psutil.WINDOWS:

497

capabilities['platform'] = 'Windows'

498

capabilities['process_priority'] = hasattr(psutil, 'HIGH_PRIORITY_CLASS')

499

elif psutil.OSX:

500

capabilities['platform'] = 'macOS'

501

502

# Check sensor capabilities

503

capabilities['battery_info'] = hasattr(psutil, 'sensors_battery')

504

capabilities['sensors'] = hasattr(psutil, 'sensors_temperatures')

505

506

return capabilities

507

508

# Get system capabilities

509

caps = get_system_capabilities()

510

print("System capabilities:", caps)

511

```

512

{ .api }

513

514

## Related Documentation

515

516

- [Process Management](process.md) - Using process status constants

517

- [System Information](system-info.md) - Platform-specific system functions

518

- [Sensors](sensors.md) - Power management constants

519

- [Exceptions](exceptions.md) - Exception handling with constants