为了连接到现有的命名管道,您可以使用CreateFile
API 通过提供pywin32
包裹。由于我花了一段时间才将工作基础放在一起,这里有一个示例客户端/服务器,它对我来说效果很好(Windows 10 Pro x64 上的 python 3.6.5、pywin32 223):
import time
import sys
import win32pipe, win32file, pywintypes
def pipe_server():
print("pipe server")
count = 0
pipe = win32pipe.CreateNamedPipe(
r'\\.\pipe\Foo',
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
1, 65536, 65536,
0,
None)
try:
print("waiting for client")
win32pipe.ConnectNamedPipe(pipe, None)
print("got client")
while count < 10:
print(f"writing message {count}")
# convert to bytes
some_data = str.encode(f"{count}")
win32file.WriteFile(pipe, some_data)
time.sleep(1)
count += 1
print("finished now")
finally:
win32file.CloseHandle(pipe)
def pipe_client():
print("pipe client")
quit = False
while not quit:
try:
handle = win32file.CreateFile(
r'\\.\pipe\Foo',
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0,
None,
win32file.OPEN_EXISTING,
0,
None
)
res = win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)
if res == 0:
print(f"SetNamedPipeHandleState return code: {res}")
while True:
resp = win32file.ReadFile(handle, 64*1024)
print(f"message: {resp}")
except pywintypes.error as e:
if e.args[0] == 2:
print("no pipe, trying again in a sec")
time.sleep(1)
elif e.args[0] == 109:
print("broken pipe, bye bye")
quit = True
if __name__ == '__main__':
if len(sys.argv) < 2:
print("need s or c as argument")
elif sys.argv[1] == "s":
pipe_server()
elif sys.argv[1] == "c":
pipe_client()
else:
print(f"no can do: {sys.argv[1]}")
输出客户端示例
> python pipe_test.py c
pipe client
no pipe, trying again in a sec
no pipe, trying again in a sec
no pipe, trying again in a sec
message: (0, b'0')
message: (0, b'1')
message: (0, b'2')
message: (0, b'3')
message: (0, b'4')
message: (0, b'5')
message: (0, b'6')
message: (0, b'7')
message: (0, b'8')
message: (0, b'9')
broken pipe, bye bye
输出服务器示例
> python pipe_test.py s
pipe server
waiting for client
got client
writing message 0
writing message 1
writing message 2
writing message 3
writing message 4
writing message 5
writing message 6
writing message 7
writing message 8
writing message 9
finished now
显然,您需要对各种调用进行一些错误检查,但这应该可行。
附注:我的一位同事遇到了问题,当客户端尝试对其执行 I/O 时,管道被关闭(异常声称“所有管道实例都忙”)。原来他用的是os.path.exists
在客户端代码中测试运行前命名管道是否已经存在CreateFile
在上面。这不知何故打破了管道。所以使用上面的方法(CreateFile
包装在 try-except 中)是尝试连接到管道直到服务器端创建管道的安全方法。