Python PySerial 读取行超时

发布于 2024-09-13 14:21:58 字数 418 浏览 1 评论 0原文

我正在使用 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() 是否超时。

I'm using pyserial to communicate with a embedded devise.

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'

if the devise cant replay then readline() times-out and 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.

Is there a nice way to check if readline() has timed-out other than checking the state of z.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

守护在此方 2024-09-20 14:21:58

我想你可能想做的是..

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

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')
以为你会在 2024-09-20 14:21:58

PySerial 有 read_until 方法正是为此,它读取序列号,直到找到预期的序列(默认为“\n”)、超出大小或直到发生超时。

PySerial has read_until method exactly for this, it reads the serial until an expected sequence is found (‘\n’ by default), the size is exceeded or until timeout occurs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文