Python多进程Listener-Client双向通信故障排查与方案咨询
进程间双向通信问题排查与解决方案
问题描述
需要实现两个Python进程的双向通信:
Listener.py后台无限循环运行,等待请求Client.py按需执行,发送字典类型数据给Listener- Listener接收数据后处理,返回结果;Client等待响应并输出/保存
当前代码运行异常:Listener能接收Client发送的数据,但崩溃且不返回响应。
错误原因分析
现有代码的核心问题有三个:
- 函数调用参数不匹配:
do_something函数定义要求传入img_path参数,但调用时done_something = do_something()未传参,触发TypeError。宽泛的except捕获了异常但未输出具体信息,导致无法定位问题,同时后续响应逻辑被中断,Client一直阻塞在recv()。 - 未正确关闭连接:Listener处理完请求后没有关闭
connection,导致资源泄漏,后续连接可能出现异常。 - 异常捕获过于笼统:
except:捕获所有异常但未打印具体错误,无法快速定位问题根源。
修正后的代码
修正版Listener.py
import time from multiprocessing.connection import Listener # 设置 address = ("localhost", 6000) listener = Listener(address, authkey=b"Passwort") # 调整函数:若不需要img_path参数则删除形参;若需要则在调用时传入对应值 def do_something(): time.sleep(1) return "I slept for 1 sec.." if __name__ == "__main__": while True: connection = listener.accept() try: conn_in = connection.recv() print(f"收到数据: {conn_in}") if conn_in is not None: # 调用函数时匹配参数要求 done_something = do_something() connection.send({ "how long I slept": done_something, "you told me": conn_in["tale"] }) except Exception as e: # 打印具体异常信息,方便调试 print(f"发生错误: {str(e)}") finally: # 确保连接被关闭,释放资源 connection.close() time.sleep(0.5)
Client.py(无需修改,保持原代码即可)
from multiprocessing.connection import Client address = ("localhost", 6000) with Client(address, authkey=b"Passwort") as connection: connection.send({"tale": "Once upon a time..."}) response = connection.recv() print(response)
替代实现方案
如果需要更灵活或稳定的进程间通信,推荐以下几种方式:
- ZeroMQ(pyzmq):轻量级消息队列库,支持请求-响应、发布-订阅等多种通信模式,适合复杂多进程场景。
- Redis:利用Redis的队列或发布订阅功能实现通信,支持跨机器、多进程并发,可靠性高。
- 原生socket:直接使用
socket模块实现TCP/UDP通信,可完全自定义通信协议,适合底层需求场景。
内容的提问来源于stack exchange,提问作者Manuel Popp
相关产品推荐
相关产品推荐

