Ubuntu20.04下Python如何解析psutil.sensors_temperatures()返回值获取CPU温度
问题解决及解析
报错原因
sensors_temperatures()返回的字典中,每个硬件类型对应的value是shwtemp对象组成的列表,不存在名为shwtemp的字典key,你之前的写法把列表当成了嵌套字典,所以会报错。
正确解析示例
通用读取逻辑
字典的每个key对应一类硬件,取到对应的列表后,通过下标访问单个shwtemp对象,再用.访问对象的label/current/high/critical属性即可:
import psutil # 获取所有温度数据 all_temps = psutil.sensors_temperatures() # 读取nvme硬盘温度示例 if 'nvme' in all_temps: nvme_item = all_temps['nvme'][0] print(f"硬盘温度:{nvme_item.label} {nvme_item.current}°C")
读取CPU温度的实现
Intel CPU的温度数据默认在coretemp对应的列表中,其中Package id 0是CPU整体封装温度,其余项对应各个物理核心的温度:
def get_cpu_temp(): all_temps = psutil.sensors_temperatures() # 兼容Intel/AMD不同的键名 cpu_temp_keys = ['coretemp', 'k10temp', 'cpu_thermal'] cpu_key = None for key in cpu_temp_keys: if key in all_temps: cpu_key = key break if not cpu_key: return None, "未检测到CPU温度传感器" cpu_temps = [] package_temp = None for item in all_temps[cpu_key]: cpu_temps.append((item.label, item.current)) if 'Package id' in item.label or 'Tdie' in item.label: package_temp = item.current return package_temp, cpu_temps # 调用示例 package_temp, core_temps = get_cpu_temp() if package_temp: print(f"CPU整体温度:{package_temp}°C") for label, temp in core_temps: print(f"{label}: {temp}°C")
更优方案说明
- 上述实现加入了CPU键名兼容逻辑,可同时适配Intel、AMD的多数消费级CPU,避免单一键名匹配失败的问题
- 优先读取
Package id(Intel)或Tdie(AMD)的温度作为CPU整体温度,比手动计算核心平均温度更准确 - 可根据需求添加异常捕获逻辑,适配部分传感器缺失的设备
内容的提问来源于stack exchange,提问作者AZZlOl
相关产品推荐
相关产品推荐

