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

Python报错NameError: name 'temp_output' is not defined,请求排查解决

解决温度传感器代码中的NameError: name 'temp_output' is not defined问题

我来帮你排查这个报错的原因,其实问题很明显,咱们一步步拆解:

错误根源

  1. 重复定义函数:你写了两个Read_Temp函数,后面那个未完成的版本直接覆盖了前面的函数,而这个半成品函数里根本没定义temp_output变量,运行时自然会抛出NameError。
  2. 逻辑不完整:第一个Read_Temp函数只实现了等待传感器就绪的逻辑,没有完成读取温度值的核心代码,这也是你想补写但出问题的原因。

修复后的完整代码

import os
import time

# 加载温度传感器所需的内核模块
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# 替换为你的传感器实际设备路径
temp_sensor = '/sys/bus/w1/devices/28-0000095ea98a/w1_slave'

def Temp_Raw():
    # 读取传感器的原始输出内容
    f = open(temp_sensor, 'r')
    lines = f.readlines()
    f.close()
    return lines

def Read_Temp():
    lines = Temp_Raw()
    # 循环等待传感器返回有效数据(末尾为YES表示数据就绪)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = Temp_Raw()
    # 定位温度值的起始位置(这就是你缺失的temp_output定义)
    temp_output = lines[1].find('t=')
    if temp_output != -1:
        # 解析原始温度字符串,转换为摄氏度
        temp_string = lines[1].strip()[temp_output+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c

# 测试温度读取功能
if __name__ == '__main__':
    try:
        while True:
            print(f"当前温度: {Read_Temp()} °C")
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序已终止")

关键修复点说明

  • 删除了重复的Read_Temp函数定义,保留并完善了第一个版本
  • 补充了temp_output的定义:通过lines[1].find('t=')定位传感器输出中温度值的起始位置
  • 添加了温度值解析逻辑,把传感器返回的原始字符串(比如t=25678)转换成实际的摄氏度数值
  • 增加了测试代码,让你可以直接运行程序看到实时温度输出

内容的提问来源于stack exchange,提问作者Zana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:58:46