PySerial: how to understand that a timeout occurred while reading from a serial port?

I use PySerialto read from the serial port, as in the code below. CheckReadUntil()read the output of the command that I send to the serial port until a sequence of characters readUntilappears in the serial output.

...

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 some reason), I just got stuck in the function CheckReadUntil()forever. The installation timeout=10sets a timeout, so I'm stuck in a loop that repeats every 10 seconds and does nothing, just waits.

How can I understand that a timeout event has occurred so that I can exit an infinite loop? Output length may vary.

+4
1

UPDATE ( , @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
+5

Source: https://habr.com/ru/post/1533126/


All Articles