2017-07-15 141 views
0

工作,我試圖讓Python失敗,如果一個COM端口未連接:的Python:pyserial超時似乎並沒有對連接

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秒後超時。

它似乎是超時「信號量超時期限已過期」。而不是實際的連接嘗試。

回答

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或其他非零數字來表示失敗。

+0

這似乎工作!!!!!! Woooooot!你是男人還是女人!無論你是什麼,你都很棒!謝謝! :) – user2654735

相關問題