1

このプログラムは、コンソールが 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)
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 に答える