为了连接到现有的命名管道,您可以使用CreateFile通过pywin32包提供的API 。由于我花了一段时间将一个工作基地放在一起这是一个示例客户端/服务器,它适用于我(python 3.6.5,Windows 10 Pro x64上的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}")
some_data = str.encode(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中)是尝试连接到管道的安全方法,直到它由服务器端创建。