在断开连接时处理pyserial中的异常

时间:2015-02-13 21:53:04

标签: python exception pyserial

我有从串口读取数据的代码。

try: 
  dataIn = self.port.read(100) 
except serial.SerialException: 
  #do some work
  return None

如果我断开设备,我会抓住我无法处理的异常。

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/serial/serialposix.py", line 475, in read
    raise SerialException('device reports readiness to read but returned no data (device disconnected or multiple access on port?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/katkov/work/obd2rds/obd2rds/testing/python/main.py", line 48, in <module>
    main()
  File "/home/katkov/work/obd2rds/obd2rds/testing/python/main.py", line 41, in main
    dataIn = serPort.read()
  File "/home/katkov/work/obd2rds/obd2rds/testing/python/uart.py", line 55, in read
    dataIn = self.port.read(100)
  File "/usr/local/lib/python3.4/dist-packages/serial/serialposix.py", line 480, in read
    if e[0] != errno.EAGAIN:
TypeError: 'SerialException' object does not support indexing

如何捕获正确处理的异常。 谢谢!

2 个答案:

答案 0 :(得分:7)

感谢Jonathan Eunice!你的建议解决了我的问题。

现在我使用以下代码:

try:
    dataIn = self.port.read()
except serial.SerialException as e:
    #There is no new data from serial port
    return None
except TypeError as e:
    #Disconnect of USB->UART occured
    self.port.close()
    return None
else:
    #Some data was received
    return dataIn

答案 1 :(得分:2)

您没有分享您的完整代码,但如果您尝试索引错误编号,那么AFAIK将无法运行。尝试:

try: 
  dataIn = self.port.read(100) 
except serial.SerialException as e:
  # ...
  if e.errno != errno.EAGAIN:
  # ...

此外,如果您在异常处理程序中工作可能导致进一步的异常,那么嵌套处理程序。 E.g:

try: 
  dataIn = self.port.read(100) 
except serial.SerialException as e:
  try:
    # more dangerous stuff
  except serial.SerialException as e2:
    # handle nested expression