pythonwindows管道_python – Windows上os.pipe上的非阻塞读取

通过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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值