如何通过一行Python代码查询运行程序的计算机CPU信息?
Absolutely! You can grab your system's CPU details in a single line of Python—here are a few practical options tailored to different needs:
Cross-Platform (Third-Party Library)
If you don’t mind installing a lightweight, widely-used system monitoring library (psutil), this line works seamlessly across Windows, Linux, and macOS, and returns comprehensive CPU specs:
import psutil; print("\n".join([f"{k}: {v}" for k, v in psutil.cpu_info()._asdict().items()]))
Just install psutil first with pip install psutil. This will print everything from the CPU model name and core count to maximum clock speed.
Pure Built-In Modules (No Extra Installs)
If you want to stick strictly to Python’s standard library, use subprocess with OS-specific commands wrapped in a conditional. This line covers all major operating systems:
import platform, subprocess; print(subprocess.check_output("wmic cpu get Name,NumberOfCores,MaxClockSpeed" if platform.system() == "Windows" else "sysctl -n machdep.cpu.brand_string hw.ncpu hw.cpufrequency" if platform.system() == "Darwin" else "lscpu | grep -E 'Model name|CPU\(s\)|CPU MHz'", shell=True).decode())
It pulls key details like CPU name, core count, and clock speed by calling native system tools (wmic for Windows, sysctl for macOS, lscpu for Linux).
Super Simple: Just the CPU Model Name
If you only need the CPU’s brand and model, here’s an even shorter one-liner for each OS:
- Windows:
import subprocess; print(subprocess.check_output("wmic cpu get Name", shell=True).decode().strip().split('\n')[1]) - Linux/macOS:
import platform, subprocess; print(subprocess.check_output("sysctl -n machdep.cpu.brand_string" if platform.system() == "Darwin" else "cat /proc/cpuinfo | grep 'model name' | head -n1 | cut -d: -f2", shell=True).decode().strip())
内容的提问来源于stack exchange,提问作者OliveProgrammer

