You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:12:34