运行CPU高负载程序时防止电脑关机,获取CPU温度失败问题排查
无法获取CPU温度的问题分析与解决办法
你当前代码的核心问题是用错了库:cpuinfo这个工具仅用于获取CPU的硬件基础信息(比如型号、核心数、架构版本等),它从设计上就不支持读取CPU温度传感器的数据,所以你调用info.get('temperature', None)必然会返回None,导致无法获取温度。
解决思路:换用支持传感器读取的库
跨平台最常用的是psutil,它能兼容Windows、Linux、macOS,支持读取系统各类传感器数据。以下是调整后的完整代码示例:
第一步:安装依赖
执行命令安装所需库:
pip install psutil colorama
第二步:修改后的代码
import psutil from colorama import Fore, init # 初始化colorama init(autoreset=True) # 获取CPU温度的函数(适配多平台) def get_cpu_temperature(): try: temps = psutil.sensors_temperatures() # 不同硬件的传感器名称可能不同,常见的有coretemp、cpu_thermal、cpu等 for sensor_name in ['coretemp', 'cpu_thermal', 'cpu']: if sensor_name in temps: # 返回第一个核心的温度,也可以取平均值:sum(t.current for t in temps[sensor_name])/len(temps[sensor_name]) return temps[sensor_name][0].current return None except Exception as e: return f"{Fore.CYAN}获取温度出错: {e}" # 带颜色显示温度的函数 def display_temperature(temperature): if isinstance(temperature, str): # 如果返回的是错误字符串,直接打印 print(temperature) return if temperature is None: print(f"{Fore.CYAN}无法获取CPU温度数据") else: temp_str = f"CPU温度: {temperature:.1f}°C" if temperature < 40: print(f"{Fore.GREEN}{temp_str}") elif temperature < 70: print(f"{Fore.YELLOW}{temp_str}") else: print(f"{Fore.RED}¡ALERTA! {temp_str}") # 执行逻辑 temperature = get_cpu_temperature() display_temperature(temperature)
额外注意事项
- 部分Windows设备需要管理员权限运行脚本才能读取传感器数据;
- 老旧硬件或部分品牌机可能未开放温度传感器接口,此时无法通过软件读取;
- 若要实现声音警报,可以添加
playsound库(pip install playsound),在温度达到阈值时调用playsound('alert.wav')播放提示音; - Linux系统也可以直接读取sysfs文件(
/sys/class/thermal/thermal_zone0/temp),数值为毫摄氏度,需除以1000转换为摄氏度。
内容的提问来源于stack exchange,提问作者iResolve ExOs
相关产品推荐
相关产品推荐

