Python PySerial:如何理解从串口读取时发生超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22605164/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:15:54  来源:igfitidea点击:

PySerial: how to understand that the timeout occured while reading from serial port?

pythonserial-porttimeoutpyserial

提问by Konstantin

I'm using PySerialto read from serial port like in the code below. CheckReadUntil()read output of the command that I send to serial port until the sequence of symbols readUntilare in the serial output.

我正在使用PySerial像下面的代码一样从串行端口读取。 CheckReadUntil()读取我发送到串行端口的命令的输出,直到符号序列readUntil在串行输出中。

...

self.ser = serial.Serial(comDev, 115200, timeout=10)

...

#Function that continue to read from Serial port until 'readUntil' 
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
    outputCharacters = []
    while 1:
        ch = self.ser.read()
        outputCharacters += ch
        if outputCharacters[-len(readUntil):]==readUntil:
            break
    outputLines = ''.join(outputCharacters)
    return outputLines

However, if there is no sequence readUntil(for any reason), I'm just stuck in the function CheckReadUntil()forever. The setting timeout=10sets up timeout so I'm stuck in a loop that iterates every 10 seconds and does nothing, just waiting.

但是,如果没有序列readUntil(出于任何原因),我就会CheckReadUntil()永远停留在函数中。该设置timeout=10设置了超时,所以我陷入了一个循环,每 10 秒迭代一次,什么都不做,只是在等待。

How it is possible to understand that there was a timeout event so I may exit the infinite loop? Output length may be different.

怎么可能理解有一个超时事件,所以我可以退出无限循环?输出长度可能不同。

采纳答案by Fookatchu

UPDATE(previous answer was not correct, this is the working code from @konstantin):

更新(以前的答案不正确,这是@konstantin 的工作代码):

...

self.ser = serial.Serial(comDev, 115200, timeout=10)

...

#Function that continue to read from Serial port until 'readUntil' 
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
    outputCharacters = []
    while 1:
        ch = self.ser.read()
        if len(ch) == 0:
            break
        outputCharacters += ch
        if outputCharacters[-len(readUntil):]==readUntil:
            break
    outputLines = ''.join(outputCharacters)
    return outputLines