这个问题-How to read from an os.pipe() without getting blocked?-显示了一个解决方案,如何检查os.pipe
是否有任何Linux数据,为此,您需要将管道置于非阻塞模式:
import os, fcntl
fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK)
在Windows上,我们有:
ImportError: No module named fcntl
但是os.pipe
有:
>>> os.pipe()
(3, 4)
那么,是否可以在Windows上执行无阻塞读取或查看os.pipe
的内容?
通过StackOverflow挖掘了一段时间后回答了我自己的问题。
更新:感谢@HarryJohnston,一切都变了。
首先,答案是否定的,在Windows上不可能进行非阻塞读取。从this answer我得到了:
Windows上的
os.pipe
是通过CreatePipe
API实现的(请参见here和。。。我在Python sources中找不到os.pipe
代码。CreatePipe
生成匿名管道,以及anonymous pipes do not support asynchronous I/O。但随后@HarryJohnston评论说,SetNamedPipeHandleState文档允许将匿名管道置于非阻塞模式。我写了测试,但是失败了。错误消息似乎是错误的,所以我试图在数据不可用时检查非阻塞读取操作的返回结果,在读取MSDN note on named pipe modes之后,我发现应该是
ERROR_NO_DATA
的int值为232。向异常处理程序添加ctypes.WinError()
调用显示了预期的[Error 232] The pipe is being closed.
所以,答案是是的,在Windows上可以进行无阻塞读取,下面是证据:
相关问题 更多 >
编程相关推荐