pySerial - UnboundLocalError:赋值前引用的局部变量'serial_port'

时间:2013-06-14 15:34:47

标签: python pyserial logfile

我得到了这个程序来保存一个日志文件,说明控制台打印出的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)

1 个答案:

答案 0 :(得分:1)

获得例外时需要退出函数:

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为例;你的脚本会破坏。您可能应该重新引发异常,或返回合适的默认值。