Python与C# WFA双向命名管道连接异常及优化求助
Python与C# WinForms应用双向命名管道连接问题
我遇到了Python脚本与C# WinForms应用之间的双向管道连接难题。两天前代码还能正常运行,但现在启动脚本后却无法建立连接,这十分反常。
C# 连接代码
if (result == DialogResult.Yes) { Thread t = new Thread(() => { // 创建命名管道服务端 NamedPipeServerStream server = new NamedPipeServerStream("mypipe"); // 等待客户端连接 server.WaitForConnection(); // 向客户端发送数据 byte[] data = Encoding.UTF8.GetBytes("Hello from C#!"); server.Write(data, 0, data.Length); // 断开连接并清理资源 server.Disconnect(); server.Dispose(); }); t.Start(); this.Close(); Application.Exit(); }
Python 调用代码
# 并行启动C#子进程 p = subprocess.Popen(['C:/Users/.../source/repos/UI_Variables_Prompt/UI_Variables_Prompt/bin/Debug/UI_Variables_Prompt.exe', str(calculation_tool)]) p.wait() # 连接命名管道服务端 client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) # 接收服务端数据 data = win32file.ReadFile(client, 4096)[1].decode('utf-8') print(data) # 断开连接并清理资源 win32file.CloseHandle(client)
calculation_tool变量已成功发送至C#,但当我点击确认按钮触发C#中的if (result == DialogResult.Yes)分支时,进程出现冻结,数据似乎无法发送。我已为此困扰两小时,未能找到解决方案,恳请帮助!
编辑1
你Python代码里的
p.wait()会一直等待进程终止。但进程要完成通信才会终止,而Python又在等着进程终止才去通信,这就死锁了。绝对不能在这里用p.wait()。—— Tim Roberts
这个说法是正确的,但移除p.wait()后,Python会尝试与不存在的管道通信,因为C#进程在建立连接前就已终止,报错如下:
client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.')
编辑2
改用try-except循环替代p.wait()后可以正常运行,但首次连接总会抛出上述报错,需要等待几秒才能连接成功。如何修改代码优化连接等待体验?
# 连接命名管道服务端 connected = False while not connected: try: client = win32file.CreateFile(r'\\.\pipe\mypipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) connected = True print('Connected') except: print('Failed to connect to named pipe, retrying in 5 seconds...') time.sleep(5)
内容的提问来源于stack exchange,提问作者Jakub Szurlej
相关产品推荐
相关产品推荐

