Get CPU info with pure Python
npx @tessl/cli install tessl/pypi-py-cpuinfo@9.0.0A 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.
pip install py-cpuinfofrom cpuinfo import get_cpu_infoAdditional imports:
from cpuinfo import get_cpu_info_json, CPUINFO_VERSION, CPUINFO_VERSION_STRINGInternal/advanced imports (not recommended for general use):
from cpuinfo import CAN_CALL_CPUID_IN_SUBPROCESS, g_trace, Trace, DataSource, ASM, CPUIDfrom cpuinfo import get_cpu_info
# Get comprehensive CPU information as a dictionary
info = get_cpu_info()
# Display basic CPU details
print(f"Processor: {info.get('brand_raw', 'Unknown')}")
print(f"Architecture: {info.get('arch', 'Unknown')}")
print(f"Cores: {info.get('count', 'Unknown')}")
print(f"Frequency: {info.get('hz_advertised_friendly', 'Unknown')}")
# Access specific information
if 'flags' in info:
print(f"CPU Features: {', '.join(info['flags'][:10])}...") # First 10 features
# Get as JSON string for serialization
import json
cpu_json = get_cpu_info_json()
parsed = json.loads(cpu_json)Retrieves comprehensive CPU information using the best available sources for the current operating system.
def get_cpu_info():
"""
Returns comprehensive CPU information using optimal detection methods for the current OS.
Returns:
dict: Complete CPU information including architecture, performance, cache, and feature details
Dictionary Keys:
- python_version (str): Python version information
- cpuinfo_version (tuple): Package version as (major, minor, patch)
- cpuinfo_version_string (str): Package version as string
- 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)
- bits (int): Architecture word size (32 or 64)
- count (int): Number of CPU cores
- brand_raw (str): Raw CPU brand string
- vendor_id_raw (str): Raw vendor identifier
- hz_advertised (tuple): Advertised frequency as (hz, precision)
- hz_actual (tuple): Actual frequency as (hz, precision)
- hz_advertised_friendly (str): Human-readable advertised frequency
- hz_actual_friendly (str): Human-readable actual frequency
- l1_data_cache_size (int): L1 data cache size in bytes
- l1_instruction_cache_size (int): L1 instruction cache size in bytes
- l2_cache_size (int): L2 cache size in bytes
- l2_cache_line_size (int): L2 cache line size in bytes
- l2_cache_associativity (int): L2 cache associativity
- l3_cache_size (int): L3 cache size in bytes
- family (int): CPU family number
- model (int): CPU model number
- stepping (int): CPU stepping number
- processor_type (int): Processor type identifier
- flags (list[str]): CPU feature flags and capabilities
- hardware_raw (str): Raw hardware identifier
- arch_string_raw (str): Raw architecture string
"""Returns the same comprehensive CPU information as a JSON-formatted string for serialization and storage.
def get_cpu_info_json():
"""
Returns comprehensive CPU information as a JSON string.
Returns:
str: CPU information in JSON format, containing same data as get_cpu_info()
"""Provides command-line access to CPU information with various output options.
def main():
"""
Command-line interface entry point.
Supports arguments:
--help: Show usage information
--json: Output information in JSON format
--version: Display package version
--trace: Enable execution tracing to file
Returns:
None
"""CPUINFO_VERSION: tuple[int, int, int]
# Package version as tuple (major, minor, patch)
# Current value: (9, 0, 0)
CPUINFO_VERSION_STRING: str
# Package version as dot-separated string
# Current value: "9.0.0"The package provides both module execution and console script access:
# Run as installed console script
cpuinfo
# Run as Python module
python -m cpuinfo
# Available options
cpuinfo --help # Show help
cpuinfo --json # JSON output format
cpuinfo --version # Show version
cpuinfo --trace # Enable tracingpy-cpuinfo automatically selects the best available method for each operating system:
When using with PyInstaller, include freeze_support for proper multiprocessing:
if __name__ == '__main__':
from cpuinfo import get_cpu_info
from multiprocessing import freeze_support
freeze_support() # Required for PyInstaller
info = get_cpu_info()
print(info)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.
⚠️ 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.
CAN_CALL_CPUID_IN_SUBPROCESS: bool
# Controls whether CPUID operations can be performed in subprocess
# Current value: True
g_trace: Trace
# Global trace instance for debugging (usually inactive)Internal debugging and tracing utility for development purposes.
class Trace:
def __init__(self, is_active: bool, is_stored_in_string: bool):
"""
Initialize trace instance.
Parameters:
is_active: Whether tracing is enabled
is_stored_in_string: Store output in string vs file
"""
def header(self, msg: str) -> None:
"""Log header message with file/line info"""
def success(self) -> None:
"""Log success message"""
def fail(self, msg: str | Exception) -> None:
"""Log failure message"""
def write(self, msg: str) -> None:
"""Write arbitrary message to trace"""Internal abstraction layer for platform-specific data sources.
class DataSource:
# Platform detection attributes
bits: str # Architecture bits ("32bit" or "64bit")
cpu_count: int # Number of CPU cores
is_windows: bool # Whether running on Windows
arch_string_raw: str # Raw architecture string
uname_string_raw: str # Raw uname string
can_cpuid: bool # Whether CPUID is available
# Static methods for checking data source availability
@staticmethod
def has_proc_cpuinfo() -> bool: ...
@staticmethod
def has_dmesg() -> bool: ...
@staticmethod
def has_lscpu() -> bool: ...
# ... additional has_* methods for various platform toolsLow-level assembly execution utility for CPUID operations.
class ASM:
def __init__(self, restype=None, argtypes=(), machine_code=[]):
"""
Create assembly function wrapper.
Parameters:
restype: Return type for ctypes
argtypes: Argument types for ctypes
machine_code: List of machine code bytes
"""
def compile(self) -> None:
"""Compile machine code into executable memory"""
def run(self, *args):
"""Execute the compiled assembly code"""
def free(self) -> None:
"""Free allocated memory"""Low-level CPU identification through assembly CPUID instruction.
class CPUID:
def __init__(self, trace=None):
"""
Initialize CPUID interface.
Parameters:
trace: Optional Trace instance for debugging
"""
def get_vendor_id(self) -> tuple[int, int, int]:
"""Get CPU vendor ID from CPUID"""
def get_info(self) -> tuple[int, int, int, int]:
"""Get basic CPU info from CPUID"""
def get_flags(self, max_extension_support: int) -> list[str]:
"""Get CPU feature flags from CPUID"""