Python serial.readline() not blocking

10,085

readline() uses the same timeout value you passed to serial.Serial(). If you want readline to be blocking, just delete the timeout argument, the default value is None.

You could also set it to None before calling readline(), if you want to have a timeout for openening the device:

import serial
try:
    device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
except:
    #Exception handeling
device.flushInput()
device.write("command")
device.timeout=None
response = device.readline()
print response
Share:
10,085
Rachie
Author by

Rachie

Updated on June 04, 2022

Comments

  • Rachie
    Rachie almost 2 years

    I'm trying to use hardware serial port devices with Python, but I'm having timing issues. If I send an interrogation command to the device, it should respond with data. If I try to read the incoming data too quickly, it receives nothing.

    import serial
    device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
    device.flushInput()
    device.write("command")
    response = device.readline()
    print response
    ''
    

    The readline() command isn't blocking and waiting for a new line as it should. Is there a simple workaround?

    • Paul Rooney
      Paul Rooney over 7 years
      Don't know if it helps but the docs show a flush call between the write and readline. Also its difficult to understand what serial actually is and how its been configured. Can you post a more complete code example that someone could actually run and see the problem
    • paxdiablo
      paxdiablo over 7 years
      What is your timeout value set to?
    • Rachie
      Rachie over 7 years
      I expanded the example. I added the flush(), but it didn't help.