Python PySerial 读取行超时

问题描述 投票:0回答:2

我正在使用 pyserial 与嵌入式设备进行通信。

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

因此,我们向设备发送 CMD,它会回复一串以

'\n'

结尾的可变长度字符串

如果设备无法重播,则

readline()
超时并且
z=''

如果设备中断或崩溃,它会发送数据然后

readline()
超时 z 将是一个末尾没有
'\n'
的字符串。

除了检查 z 的状态之外,还有什么好方法来检查

readline()
是否超时。

python pyserial
2个回答
5
投票

我想你可能想做的是..

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')

0
投票

PySerial 有 read_until 方法正是为此,它读取序列直到找到预期的序列(‘ ’默认情况下),超出大小或直到发生超时。

© www.soinside.com 2019 - 2024. All rights reserved.