2010-08-09 132 views
4

我正在使用pyserial與嵌入式設備進行通信。Python PySerial讀取線超時

ser = serial.Serial(PORT, BAUD, timeout = TOUT) 
ser.write(CMD) 
z = ser.readline(eol='\n') 

所以我們發送CMD的設備並將其與varing長度的結局在'\n'

的串回覆,如果色器件着重播然後readline()倍出和z=''

如果色器件被中斷或崩潰它會發送數據然後readline()超時 和z將是一個沒有'\n'結尾的字符串。

有沒有一種很好的方法來檢查readline()是否超時,而不是檢查z的狀態。

回答

4

我認爲你會喜歡做的是什麼..

import re 
import time 
import serial 

def doRead(ser,term): 
    matcher = re.compile(term) #gives you the ability to search for anything 
    tic  = time.time() 
    buff = ser.read(128) 
    # you can use if not ('\n' in buff) too if you don't like re 
    while ((time.time() - tic) < tout) and (not matcher.search(buff)): 
     buff += ser.read(128) 

    return buff 

if __name__ == "__main__": 
    ser = serial.Serial(PORT, BAUD, timeout = TOUT) 
    ser.write(CMD) 
    print doRead(ser,term='\n')