如何用Python的psutil在树莓派中仅获取并打印当前CPU温度?
正确获取树莓派CPU温度的psutil代码方案
先看你当前的输出结构:{'cpu_thermal': [shwtemp(label='', current=36.998, high=None, critical=None)]},这是一个字典,其中cpu_thermal对应的是一个列表,列表里的第一个元素是shwtemp对象,包含current温度属性。
你之前的写法错误在于没有正确遍历这个嵌套结构,正确代码如下:
import psutil # 获取温度传感器数据 temp_data = psutil.sensors_temperatures() # 提取cpu_thermal列表中的第一个shwtemp对象,再取current属性 cpu_temp = temp_data['cpu_thermal'][0].current # 打印温度,可按需格式化 print(f"当前CPU温度:{cpu_temp}℃")
为什么之前的写法不生效?
psutil.sensors_temperatures().current:该方法返回的是字典,字典本身没有current属性,自然报错。psutil.sensors_temperatures().cpu_thermal.current:cpu_thermal对应的值是列表,列表也没有current属性,必须先通过索引[0]取出列表里的shwtemp对象,才能访问它的current属性。
内容的提问来源于stack exchange,提问作者Matt Clarke
相关产品推荐
相关产品推荐

