Get CPU info with pure Python
npx @tessl/cli install tessl/pypi-py-cpuinfo@9.0.00
# py-cpuinfo
1
2
A pure Python library for retrieving detailed CPU information across multiple operating systems and architectures without requiring external dependencies or compilation. py-cpuinfo provides comprehensive CPU detection capabilities including processor type, architecture, cache sizes, frequency information, and instruction set features through various OS-specific methods.
3
4
## Package Information
5
6
- **Package Name**: py-cpuinfo
7
- **Language**: Python
8
- **Installation**: `pip install py-cpuinfo`
9
10
## Core Imports
11
12
```python
13
from cpuinfo import get_cpu_info
14
```
15
16
Additional imports:
17
18
```python
19
from cpuinfo import get_cpu_info_json, CPUINFO_VERSION, CPUINFO_VERSION_STRING
20
```
21
22
Internal/advanced imports (not recommended for general use):
23
24
```python
25
from cpuinfo import CAN_CALL_CPUID_IN_SUBPROCESS, g_trace, Trace, DataSource, ASM, CPUID
26
```
27
28
## Basic Usage
29
30
```python
31
from cpuinfo import get_cpu_info
32
33
# Get comprehensive CPU information as a dictionary
34
info = get_cpu_info()
35
36
# Display basic CPU details
37
print(f"Processor: {info.get('brand_raw', 'Unknown')}")
38
print(f"Architecture: {info.get('arch', 'Unknown')}")
39
print(f"Cores: {info.get('count', 'Unknown')}")
40
print(f"Frequency: {info.get('hz_advertised_friendly', 'Unknown')}")
41
42
# Access specific information
43
if 'flags' in info:
44
print(f"CPU Features: {', '.join(info['flags'][:10])}...") # First 10 features
45
46
# Get as JSON string for serialization
47
import json
48
cpu_json = get_cpu_info_json()
49
parsed = json.loads(cpu_json)
50
```
51
52
## Capabilities
53
54
### CPU Information Retrieval
55
56
Retrieves comprehensive CPU information using the best available sources for the current operating system.
57
58
```python { .api }
59
def get_cpu_info():
60
"""
61
Returns comprehensive CPU information using optimal detection methods for the current OS.
62
63
Returns:
64
dict: Complete CPU information including architecture, performance, cache, and feature details
65
66
Dictionary Keys:
67
- python_version (str): Python version information
68
- cpuinfo_version (tuple): Package version as (major, minor, patch)
69
- cpuinfo_version_string (str): Package version as string
70
- arch (str): CPU architecture (X86_32, X86_64, ARM_7, ARM_8, PPC_32, PPC_64, SPARC_32, SPARC_64, S390X, MIPS_32, MIPS_64, RISCV_32, RISCV_64)
71
- bits (int): Architecture word size (32 or 64)
72
- count (int): Number of CPU cores
73
- brand_raw (str): Raw CPU brand string
74
- vendor_id_raw (str): Raw vendor identifier
75
- hz_advertised (tuple): Advertised frequency as (hz, precision)
76
- hz_actual (tuple): Actual frequency as (hz, precision)
77
- hz_advertised_friendly (str): Human-readable advertised frequency
78
- hz_actual_friendly (str): Human-readable actual frequency
79
- l1_data_cache_size (int): L1 data cache size in bytes
80
- l1_instruction_cache_size (int): L1 instruction cache size in bytes
81
- l2_cache_size (int): L2 cache size in bytes
82
- l2_cache_line_size (int): L2 cache line size in bytes
83
- l2_cache_associativity (int): L2 cache associativity
84
- l3_cache_size (int): L3 cache size in bytes
85
- family (int): CPU family number
86
- model (int): CPU model number
87
- stepping (int): CPU stepping number
88
- processor_type (int): Processor type identifier
89
- flags (list[str]): CPU feature flags and capabilities
90
- hardware_raw (str): Raw hardware identifier
91
- arch_string_raw (str): Raw architecture string
92
"""
93
```
94
95
### JSON CPU Information Retrieval
96
97
Returns the same comprehensive CPU information as a JSON-formatted string for serialization and storage.
98
99
```python { .api }
100
def get_cpu_info_json():
101
"""
102
Returns comprehensive CPU information as a JSON string.
103
104
Returns:
105
str: CPU information in JSON format, containing same data as get_cpu_info()
106
"""
107
```
108
109
### Command Line Interface
110
111
Provides command-line access to CPU information with various output options.
112
113
```python { .api }
114
def main():
115
"""
116
Command-line interface entry point.
117
118
Supports arguments:
119
--help: Show usage information
120
--json: Output information in JSON format
121
--version: Display package version
122
--trace: Enable execution tracing to file
123
124
Returns:
125
None
126
"""
127
```
128
129
## Constants
130
131
```python { .api }
132
CPUINFO_VERSION: tuple[int, int, int]
133
# Package version as tuple (major, minor, patch)
134
# Current value: (9, 0, 0)
135
136
CPUINFO_VERSION_STRING: str
137
# Package version as dot-separated string
138
# Current value: "9.0.0"
139
```
140
141
## Command Line Usage
142
143
The package provides both module execution and console script access:
144
145
```bash
146
# Run as installed console script
147
cpuinfo
148
149
# Run as Python module
150
python -m cpuinfo
151
152
# Available options
153
cpuinfo --help # Show help
154
cpuinfo --json # JSON output format
155
cpuinfo --version # Show version
156
cpuinfo --trace # Enable tracing
157
```
158
159
## Platform Support
160
161
### Operating Systems
162
- Windows (XP, Vista, 7, 8, 10+)
163
- Linux (Arch, CentOS, Debian, Fedora, Gentoo, OpenSUSE, Ubuntu)
164
- macOS (10.8+)
165
- BSD variants (FreeBSD, PC-BSD, TrueOS, OpenBSD, NetBSD)
166
- Solaris (Oracle Solaris, OpenIndiana)
167
- Haiku
168
- Cygwin (Windows)
169
170
### CPU Architectures
171
- X86 (32-bit and 64-bit)
172
- ARM (ARM_7, ARM_8)
173
- PowerPC (PPC_32, PPC_64)
174
- SPARC (SPARC_32, SPARC_64)
175
- S390X
176
- MIPS (MIPS_32, MIPS_64)
177
- RISC-V (RISCV_32, RISCV_64)
178
179
## Information Sources
180
181
py-cpuinfo automatically selects the best available method for each operating system:
182
183
1. Windows Registry (Windows)
184
2. /proc/cpuinfo (Linux)
185
3. sysctl (macOS)
186
4. dmesg (Unix/Linux)
187
5. /var/run/dmesg.boot (BSD/Unix)
188
6. isainfo and kstat (Solaris)
189
7. cpufreq-info (BeagleBone)
190
8. lscpu (Unix/Linux)
191
9. sysinfo (Haiku)
192
10. Device-tree IBM features flags (Linux PPC)
193
11. CPUID register queries (Intel X86 CPUs)
194
195
## PyInstaller Compatibility
196
197
When using with PyInstaller, include freeze_support for proper multiprocessing:
198
199
```python
200
if __name__ == '__main__':
201
from cpuinfo import get_cpu_info
202
from multiprocessing import freeze_support
203
204
freeze_support() # Required for PyInstaller
205
info = get_cpu_info()
206
print(info)
207
```
208
209
## Error Handling
210
211
The library is designed for robustness - it returns partial information when some detection methods fail rather than raising exceptions. Missing or unavailable CPU information fields are simply omitted from the returned dictionary.
212
213
## Internal API (Advanced Users Only)
214
215
⚠️ **Warning**: The following components are internal implementation details that are accidentally exposed through wildcard imports. They are not intended for general use and may change without notice. Use at your own risk.
216
217
### Internal Constants
218
219
```python { .api }
220
CAN_CALL_CPUID_IN_SUBPROCESS: bool
221
# Controls whether CPUID operations can be performed in subprocess
222
# Current value: True
223
224
g_trace: Trace
225
# Global trace instance for debugging (usually inactive)
226
```
227
228
### Internal Classes
229
230
#### Trace
231
232
Internal debugging and tracing utility for development purposes.
233
234
```python { .api }
235
class Trace:
236
def __init__(self, is_active: bool, is_stored_in_string: bool):
237
"""
238
Initialize trace instance.
239
240
Parameters:
241
is_active: Whether tracing is enabled
242
is_stored_in_string: Store output in string vs file
243
"""
244
245
def header(self, msg: str) -> None:
246
"""Log header message with file/line info"""
247
248
def success(self) -> None:
249
"""Log success message"""
250
251
def fail(self, msg: str | Exception) -> None:
252
"""Log failure message"""
253
254
def write(self, msg: str) -> None:
255
"""Write arbitrary message to trace"""
256
```
257
258
#### DataSource
259
260
Internal abstraction layer for platform-specific data sources.
261
262
```python { .api }
263
class DataSource:
264
# Platform detection attributes
265
bits: str # Architecture bits ("32bit" or "64bit")
266
cpu_count: int # Number of CPU cores
267
is_windows: bool # Whether running on Windows
268
arch_string_raw: str # Raw architecture string
269
uname_string_raw: str # Raw uname string
270
can_cpuid: bool # Whether CPUID is available
271
272
# Static methods for checking data source availability
273
@staticmethod
274
def has_proc_cpuinfo() -> bool: ...
275
@staticmethod
276
def has_dmesg() -> bool: ...
277
@staticmethod
278
def has_lscpu() -> bool: ...
279
# ... additional has_* methods for various platform tools
280
```
281
282
#### ASM
283
284
Low-level assembly execution utility for CPUID operations.
285
286
```python { .api }
287
class ASM:
288
def __init__(self, restype=None, argtypes=(), machine_code=[]):
289
"""
290
Create assembly function wrapper.
291
292
Parameters:
293
restype: Return type for ctypes
294
argtypes: Argument types for ctypes
295
machine_code: List of machine code bytes
296
"""
297
298
def compile(self) -> None:
299
"""Compile machine code into executable memory"""
300
301
def run(self, *args):
302
"""Execute the compiled assembly code"""
303
304
def free(self) -> None:
305
"""Free allocated memory"""
306
```
307
308
#### CPUID
309
310
Low-level CPU identification through assembly CPUID instruction.
311
312
```python { .api }
313
class CPUID:
314
def __init__(self, trace=None):
315
"""
316
Initialize CPUID interface.
317
318
Parameters:
319
trace: Optional Trace instance for debugging
320
"""
321
322
def get_vendor_id(self) -> tuple[int, int, int]:
323
"""Get CPU vendor ID from CPUID"""
324
325
def get_info(self) -> tuple[int, int, int, int]:
326
"""Get basic CPU info from CPUID"""
327
328
def get_flags(self, max_extension_support: int) -> list[str]:
329
"""Get CPU feature flags from CPUID"""
330
```