gpt4 book ai didi

python - pySerial-UnboundLocalError : local variable 'serial_port' referenced before assignment

转载 作者:太空宇宙 更新时间:2023-11-03 18:56:44 25 4
gpt4 key购买 nike

我得到这个程序来保存控制台从 USB 连接设备(无线传感器)打印的日志文件。它产生错误:

UnboundLocalError: local variable 'serial_port' referenced before assignment.

它是经过修改的 pySerial.py 以满足我的应用程序的需求。它记录控制台打印内容的一部分(最好我想记录所有内容)

我对python不熟悉,所以我无法自己解决这个问题。非常欢迎您的帮助!代码哪里出错了?

import serial
import io
import time

def serial_com():
'''Serial communications: get a response'''
# open serial port
try:
serial_port = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1)
except serial.SerialException as e:
print("could not open serial port '{}': {}".format('/dev/ttyUSB0', e))

# read response from serial port
lines = []
while True:
lines = []
line = serial_port.readline()
lines = ([time.localtime().tm_hour,
time.localtime().tm_min,
time.localtime().tm_sec,
line.decode('utf-8').rstrip()])

# wait for new data after each line
timeout = time.time() + 10
while not serial_port.inWaiting() and timeout > time.time():
pass
if not serial_port.inWaiting():
break

#close the serial port
serial_port.close()

linesplit = str(lines[3]).split()
temp1 = -40+0.01*float(linesplit[2])
output = [lines[0], lines[1], lines[2], temp1]
return output

def writeXML(lines):
from xml.etree.ElementTree import Element, SubElement, tostring, ElementTree
root = Element('CATALOG')
child1 = SubElement(root, 'Measurement')
child11 = SubElement(child1, 'Time')
child11.text = str(lines[0])+':'+str(lines[1])+':'+str(lines[2])
child12 = SubElement(child1, 'Values')
child12.text = str(round(lines[3], 2))
tree = ElementTree(root)
tree.write('/var/www/values.xml', 'UTF-8')

while True:
lines=serial_com()
writeXML(lines)
time.sleep(10)

最佳答案

当你遇到异常时,你需要退出你的函数:

try:
serial_port = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1)
except serial.SerialException as e:
print("could not open serial port '{}': {}".format('/dev/ttyUSB0', e))
return

因为如果您确实收到异常,则永远不会设置 serial_port ,从而导致 UnboundLocalError 异常。

我在这里使用return作为示例;无论哪种方式你的脚本都会中断。您可能应该重新引发异常,或返回合适的默认值。

关于python - pySerial-UnboundLocalError : local variable 'serial_port' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17112149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com