简体   繁体   中英

Python os.read blocks until newline character

I have an XBee plugged into a Raspberry PI. Here is the Python 3.4 code I am using:

f = os.open("/dev/ttyUSB0", os.O_RDWR | os.O_NONBLOCK)

print("Writing...")
b = bytes("hello","utf-8")
os.write(f,b)

print("Press return to start read")
cmd = input()

print("Reading...")
ret = os.read(f,10)
if ret == None:
        print("ret = None")
else:
        print("ret = {}".format(ret))

 os.close(f)

Yesterday, this all worked as I expected. The read command returned immediately, with zero bytes if there wasn't anything to read.

Today I added code to another part of the project that writes to a text file and includes a thread RLock. Now the above code does something different. If there are no bytes waiting to be read, or there are bytes waiting to be read but they don't end with an 0x0D, I get an error:

BlockingIOError: [Errno 11] Resource temporarily unavailable

But is there are bytes waiting to be read that end with an 0x0D, the read function returns those bytes including the 0x0D.

Update: I have reformated the system, and the fault has not gone away, which suggests it wasn't the addition of the file and thread locking code that caused the problem.

I ran minicom and the problem has gone away, so maybe I should be doing something with serial configuration on the device before I open it as a file?

This is the line that returns the os.read to its original behaviour:

minicom -b 9600 -o -D /dev/ttyUSB0

I strongly suspect that the two different behaviours are related to the CTS/RTS flow control settings on the serial port. Try turning CTS/RTS on or off to get the behaviour you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM