未定义的变量:SerialException

J3R*_*3RN 3 python exception-handling serial-port exception pyserial

我正在使用pySerial库从Arduino获取Python脚本日志数据.我正在尝试处理SerialException,当脚本无法连接到您提供的端口时,Eclipse会说"Undefined variable:SerialException".有什么我忘了导入的东西吗?

码:

try:
    ser = serial.Serial(port, 9600)
    connected = 1
except SerialException:
    print "No connection to the device could be established"
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 12

你可能想要:

except serial.SerialException:
   ...
Run Code Online (Sandbox Code Playgroud)

在python中,Exceptions是派生自的类Exception.因此,当模块/包定义它自己的自定义异常时,它们通常会像其他类/函数一样导入模块/包的命名空间中.这说,放一个:

from serial import SerialException
Run Code Online (Sandbox Code Playgroud)

在你的文件的顶部可能也会做到这一点.