gpt4 book ai didi

python - 在断开连接期间处理 pyserial 中的异常

转载 作者:太空狗 更新时间:2023-10-30 00:44:31 24 4
gpt4 key购买 nike

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

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

我怎样才能捕捉到它被正确处理的异常。谢谢!

最佳答案

感谢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

关于python - 在断开连接期间处理 pyserial 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com