Using PySerial is it possible to wait for data?

def cmd(cmd,serial):
    out='';prev='101001011'
    serial.flushInput();serial.flushOutput()
    serial.write(cmd+'\r');
    while True:
        out+= str(serial.read(1))
        if prev == out: return out
        prev=out
    return out

call it like this:

cmd('ATZ',serial.Serial('/dev/ttyUSB0', timeout=1, baudrate=115000))

Ok, I actually got something together that I like for this. Using a combination of read() with no timeout and the inWaiting() method:

#Modified code from main loop: 
s = serial.Serial(5)

#Modified code from thread reading the serial port
while 1:
  tdata = s.read()           # Wait forever for anything
  time.sleep(1)              # Sleep (or inWaiting() doesn't give the correct value)
  data_left = s.inWaiting()  # Get the number of characters ready to be read
  tdata += s.read(data_left) # Do the read and combine it with the first character

  ... #Rest of the code

This seems to give the results I wanted, I guess this type of functionality doesn't exist as a single method in Python


You can set timeout = None, then the read call will block until the requested number of bytes are there. If you want to wait until data arrives, just do a read(1) with timeout None. If you want to check data without blocking, do a read(1) with timeout zero, and check if it returns any data.

(see documentation https://pyserial.readthedocs.io/en/latest/)