简体   繁体   English

Python os.read块,直到换行符

[英]Python os.read blocks until newline character

I have an XBee plugged into a Raspberry PI. 我有一个XBee插入Raspberry PI。 Here is the Python 3.4 code I am using: 这是我正在使用的Python 3.4代码:

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. read命令立即返回,如果没有要读取的内容,则返回零字节。

Today I added code to another part of the project that writes to a text file and includes a thread RLock. 今天,我将代码添加到了该项目的另一部分,该部分写入一个文本文件,并包括一个线程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: 如果没有等待读取的字节,或者有等待读取的字节,但是它们没有以0x0D结尾,则会出现错误:

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. 但是是否有等待读取的字节以0x0D结尾,读取函数返回的字节包括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? 我运行了minicom,问题已经消失了,所以也许在我将其作为文件打开之前,应该先对设备进行串行配置吗?

This is the line that returns the os.read to its original behaviour: 这是将os.read返回其原始行为的行:

minicom -b 9600 -o -D /dev/ttyUSB0 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. 我强烈怀疑这两种不同的行为与串行端口上的CTS / RTS流控制设置有关。 Try turning CTS/RTS on or off to get the behaviour you want. 尝试打开或关闭CTS / RTS以获取所需的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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