Python循环内捕获IndexError异常报SyntaxError问题求解
错误原因
Python异常捕获语法有强制要求:except语句必须和前置的try语句配对使用,不能单独把except块直接丢在循环或者普通代码块里。你改的代码在while循环开头直接写except IndexError,根本没有用try块包裹要捕获异常的代码,解释器识别到非法语法就直接报错了。
你的代码里会触发IndexError: list index out of range的常见场景:
- 读传感器w1_slave文件时偶尔返回空/不完整内容,取
lines[0]、lines[1]的时候索引越界 - 1-Wire总线偶尔扫不到温度传感器,glob匹配不到28开头的设备文件夹,取列表第一个元素时报错
正确实现方案
调整两个核心点即可满足需求:
- 把温度读取、数据写入这类可能抛错的业务逻辑全部放进
try块,后面紧跟对应的except块捕获IndexError - 可以把工具函数移到循环外部,避免每轮循环重复定义函数产生不必要的开销,同时每轮循环重新扫描传感器设备,避免启动时传感器未接直接崩溃
修正后的完整可运行代码:
import os import glob import time import urllib import urllib2 import httplib import json from influxdb import InfluxDBClient client = InfluxDBClient(host='192.168.1.7', port=8086) client.switch_database('influxdb1') os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/devices/w1_bus_master1/' # 函数定义移到循环外,避免重复定义 def read_temp_raw(device_file): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(device_file): lines = read_temp_raw(device_file) while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw(device_file) equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 return temp_c while True: try: # 每轮重新扫描设备,兼容传感器临时离线的场景 device_folders = glob.glob(base_dir + '28*') if not device_folders: raise IndexError("未检测到温度传感器") device_folder = device_folders[0] device_file = device_folder + '/w1_slave' temp = float(read_temp(device_file)) json_body = [ { "measurement": "YOUR_MEASUREMENT", "tags": { "Device": "YOUR_DEVICE", "ID": "YOUR_ID" }, "fields": { "outside_temp": temp, } } ] client.write_points(json_body) # 正常采样完成后休眠60秒 time.sleep(60) except IndexError: # 捕获到索引越界错误,等待15秒后重试 time.sleep(15) continue
逻辑说明
- 所有可能触发索引越界的操作都被try块覆盖,不会因为传感器临时异常导致整个程序终止
- 异常触发后仅等待15秒就进入下一轮重试,匹配传感器可自行恢复的场景
- 只有正常完成采样写入后才会等待60秒,不会因为异常等待打乱正常的采样间隔
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

