通过StackOverflow挖掘一段时间后回答我自己的问题.
更新:由于@HarryJohnston,事情发生了变化.
起初答案是否定的,不可能在Windows上对os.pipe进行非阻塞读取.从this answer开始,我得到了:
The term for non-blocking / asynchronous I/O in Windows is ‘overlapped’ – that’s what you should be looking at.
Windows上的os.pipe是通过CreatePipe API实现的(参见here和……好吧,我在Python sources找不到os.pipe代码). CreatePipe生成匿名管道,anonymous pipes do not support asynchronous I/O.
但随后@HarryJohnston评论说,SetNamedPipeHandleState doc允许将匿名管道置于非阻塞模式.我写了测试,它失败了OSError:[Errno 22]参数无效.错误消息似乎是错误的,所以我试图检查当数据不可用时非阻塞读取操作应该返回什么结果,并且在读取MSDN note on named pipe modes后我发现它应该是具有int值232的ERROR_NO_DATA.添加ctypes.WinError ()调用异常处理程序显示预期[错误232]管道正在关闭.
所以,答案是肯定的,可以在Windows上对os.pipe进行非阻塞读取,这是证明:
import msvcrt
import os
from ctypes import windll, byref, wintypes, GetLastError, WinError
from ctypes.wintypes import HANDLE, DWORD, POINTER, BOOL
LPDWORD = POINTER(DWORD)
PIPE_NOWAIT = wintypes.DWORD(0x00000001)
ERROR_NO_DATA = 232
def pipe_no_wait(pipefd):
""" pipefd is a integer as returned by os.pipe """
SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
SetNamedPipeHandleState.restype = BOOL
h = msvcrt.get_osfhandle(pipefd)
res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
if res == 0:
print(WinError())
return False
return True
if __name__ == '__main__':
# CreatePipe
r, w = os.pipe()
pipe_no_wait(r)
print os.write(w, 'xxx')
print os.read(r, 1024)
try:
print os.write(w, 'yyy')
print os.read(r, 1024)
print os.read(r, 1024)
except OSError as e:
print dir(e), e.errno, GetLastError()
print(WinError())
if GetLastError() != ERROR_NO_DATA:
raise