1

I was given this program to keep a log file of what the console prints out of a usb connected device (wireless sensor). It produces the error:

UnboundLocalError: local variable 'serial_port' referenced before assignment.

It is pySerial.py modified to suit the needs of my application. It logs a part of what the console prints (preferably i would like to log everything)

I am not familiar with python so i couldn't solve this by my self. your help is very welcome!! where has the code gone wrong?

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)
4

1 回答 1

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在这里举个例子;无论哪种方式,您的脚本都会中断。您可能应该重新引发异常,或返回合适的默认值。

于 2013-06-14T15:36:23.980 回答