簡體   English   中英

Python:Pyserial超時似乎不適用於連接

[英]Python: pyserial timeout doesn't seem to work on connect

如果未連接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:\Projects\Personal\Alex_Quadcopter\mine\scripts\lib\GetData.py", line 21, in <module>
    write_timeout = 1,
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 31, in __init__
    super(Serial, self).__init__(*args, **kwargs)
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialutil.py", line 240, in __init__
    self.open()
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 78, in open
    self._reconfigure_port()
  File "C:\Users\dingleberry\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.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:\Projects\Personal\Alex_Quadcopter\mine\scripts\lib\GetData.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或其他一些非零的數字來表示失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM