从无缓冲的 os.fdopen() 文件对象中读取的行为不像 os.read()
Reading from unbuffered os.fdopen() file object doesn't behave like os.read()
我有以下代码
r, w = os.pipe()
rf, wf = os.fdopen(r, 'rb', 0), os.fdopen(w, 'wb', 0)
wf.write('hello')
用
阅读时
rf.read(10)
它永远阻塞。但是,如果我用
阅读它
os.read(r, 10)
它 returns 'hello'
无需等待 10 个字节可用。
问题是:如何使 .read()
对 os.fdopen()
的文件对象的行为相同? (又名非阻塞)
可能有更好的方法,但您可以使用 fcntl
module 设置 O_NONBLOCK
:
import fcntl
r, w = os.pipe()
fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK)
…
这可以通过使用 io.open()
而不是 os.fdopen()
来解决
请注意,您必须使用 buffering=0
才能正常工作:
rf = io.open(r, 'rb', 0)
rf.read(10)
我有以下代码
r, w = os.pipe()
rf, wf = os.fdopen(r, 'rb', 0), os.fdopen(w, 'wb', 0)
wf.write('hello')
用
阅读时rf.read(10)
它永远阻塞。但是,如果我用
阅读它os.read(r, 10)
它 returns 'hello'
无需等待 10 个字节可用。
问题是:如何使 .read()
对 os.fdopen()
的文件对象的行为相同? (又名非阻塞)
可能有更好的方法,但您可以使用 fcntl
module 设置 O_NONBLOCK
:
import fcntl
r, w = os.pipe()
fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK)
…
这可以通过使用 io.open()
而不是 os.fdopen()
请注意,您必须使用 buffering=0
才能正常工作:
rf = io.open(r, 'rb', 0)
rf.read(10)