要连接到现有的命名管道,您可以利用通过pywin32
包提供的CreateFile
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(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中)是安全的方法,直到服务器端创建了它。
f = open(r'\\.\PIPE\<pipe name>', 'rb+', buffering=0)
,然后调用f.read(nbytes)
和f.write(string)
。 - Eryk Sunstr
字符串是字节字符串。在Python 3中,您需要编写bytes
。 - Eryk Sunpython
仍然是Python 2,而运行Python 3需要使用python3
。 - Eryk Sun