Python PySerial 读取行超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3437303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python PySerial read-line timeout
提问by Ketil
I'm using pyserial to communicate with a embedded devise.
我正在使用 pyserial 与嵌入式设备进行通信。
ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol='\n')
So we send CMD to the device and it replies with an string of varing length ending in a '\n'
所以我们将 CMD 发送到设备,它会回复一个以 a 结尾的可变长度字符串 '\n'
if the devise cant replay then readline()times-out and z=''
如果设备无法重播,则readline()超时并且z=''
if the devise is interrupted or crashes will it's sending the data then readline()times-out
and z will be a string without a '\n'at the end.
如果设备被中断或崩溃,它会发送数据然后readline()超时,z 将是一个末尾没有 a 的字符串'\n'。
Is there a nice way to check if readline()has timed-out other than checking the state of z.
readline()除了检查 z 的状态之外,是否有一种很好的方法来检查是否已超时。
采纳答案by pyInTheSky
I think what you might like to do is..
我想你可能喜欢做的是..
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')

