Python:pyserial 超时似乎在连接上不起作用



如果未连接COM端口,我正在尝试让python失败:

import serial
ser = serial
print("ermrmrmrr")
try:
ser = serial.Serial(
port        = 'COM6',
baudrate    = 115200,
parity      = serial.PARITY_NONE,
stopbits    = serial.STOPBITS_ONE,
bytesize    = serial.EIGHTBITS,
timeout     = 1,
)
except:
print("what what in the butt")
ser.close()
sys.exit(0)
print("grrrrr")

输出为:

ermrmrmrr
what what in the butt
Traceback (most recent call last):
File "C:ProjectsPersonalAlex_QuadcopterminescriptslibGetData.py", line 21, in <module>
write_timeout = 1,
File "C:UsersdingleberryAppDataLocalProgramsPythonPython36-32libsite-packagesserialserialwin32.py", line 31, in __init__
super(Serial, self).__init__(*args, **kwargs)
File "C:UsersdingleberryAppDataLocalProgramsPythonPython36-32libsite-packagesserialserialutil.py", line 240, in __init__
self.open()
File "C:UsersdingleberryAppDataLocalProgramsPythonPython36-32libsite-packagesserialserialwin32.py", line 78, in open
self._reconfigure_port()
File "C:UsersdingleberryAppDataLocalProgramsPythonPython36-32libsite-packagesserialserialwin32.py", line 222, in _reconfigure_port
'Original message: {!r}'.format(ctypes.WinError()))
serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: OSError(22, 'The semaphore timeout period has expired.', None, 121)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ".PrincipalAxes.py", line 11, in <module>
from lib import GetData as gd
File "C:ProjectsPersonalAlex_QuadcopterminescriptslibGetData.py", line 25, in <module>
print("what what in the butt")

此输出还可以,除了它在尝试连接后 30 秒 - 1 分钟超时,而不是在 1 秒后超时。

它似乎在"信号灯超时期限已过期"上超时,而不是实际的连接尝试。

问题是你不能关闭ser,因为发生了致命的事情。

你应该把你的捕获分解为单独的例外,而不是一个捕获所有内容的异常。例如:

except serial.SerialException as e:
#There is no new data from serial port
print str(e)
sys.exit(1)
except TypeError as e:
print str(e)
ser.port.close()
sys.exit(1)

另请注意,通常传递 0 到sys.exit表示成功。您应该传递 1 或其他一些非零数字来表示失败。

相关内容

  • 没有找到相关文章

最新更新