Python 在异步IO服务器启动后执行协同路由
我正在开发一个控制器应用程序,用于监视和控制独立于python可执行的子流程。 基本上我想要的是在controller.py中运行asyncio.star_服务器。在服务器启动并运行之后,controller.py应该作为连接到它的客户端执行其他python文件。控制器服务器将永远运行,并创建新的客户端实例,必要时还会向它们发送关闭消息 不幸的是,这不起作用。没有收到错误,它只是挂起 controller.py:Python 在异步IO服务器启动后执行协同路由,python,asynchronous,subprocess,python-asyncio,Python,Asynchronous,Subprocess,Python Asyncio,我正在开发一个控制器应用程序,用于监视和控制独立于python可执行的子流程。 基本上我想要的是在controller.py中运行asyncio.star_服务器。在服务器启动并运行之后,controller.py应该作为连接到它的客户端执行其他python文件。控制器服务器将永远运行,并创建新的客户端实例,必要时还会向它们发送关闭消息 不幸的是,这不起作用。没有收到错误,它只是挂起 controller.py: async def handleClient(reader, writer):
async def handleClient(reader, writer):
#handling a connection
addr = writer.get_extra_info("peername")
print(f"connection from {addr}")
data_ = await reader.readline()
...
async def startClient(client_py_file, host, port):
# this executes another py file that will connect to this server
await asyncio.sleep(0.1)
subprocess.run(["python.exe", client_py_file, host, port])
async def main():
server = await asyncio.start_server(handleClient, "127.0.0.1", 4000)
await asyncio.ensure_future(startClient("client.py", "127.0.0.1", 4000)
await server.wait_closed()
asyncio.run(main())
async def async_client(loop):
reader, writer = await asyncio.open_connection(host, port, loop = loop)
writer.writelines([json.dumps("key" : idstr, "msg" : "this is my message"}, b"\n"])
await writer.drain()
while True:
data = await reader.readline()
....
它似乎执行启动的client.py,该client.py连接到服务器时没有任何错误
client.py:
async def handleClient(reader, writer):
#handling a connection
addr = writer.get_extra_info("peername")
print(f"connection from {addr}")
data_ = await reader.readline()
...
async def startClient(client_py_file, host, port):
# this executes another py file that will connect to this server
await asyncio.sleep(0.1)
subprocess.run(["python.exe", client_py_file, host, port])
async def main():
server = await asyncio.start_server(handleClient, "127.0.0.1", 4000)
await asyncio.ensure_future(startClient("client.py", "127.0.0.1", 4000)
await server.wait_closed()
asyncio.run(main())
async def async_client(loop):
reader, writer = await asyncio.open_connection(host, port, loop = loop)
writer.writelines([json.dumps("key" : idstr, "msg" : "this is my message"}, b"\n"])
await writer.drain()
while True:
data = await reader.readline()
....
现在客户端挂起并等待服务器的响应。但在服务器上不会触发handleClient处理程序。我不知道出了什么问题。你能帮帮我吗?
提前谢谢你 问题在于
subprocess.run
是一个阻塞函数,它等待客户端完成。在此等待期间,事件循环被阻止,无法为传入连接提供服务
最简单的修复方法是将
subprocess.run(…)
替换为subprocess.Popen(…)
,它执行相同的操作,但不等待子流程完成就返回一个句柄。如果您需要与子流程通信,也可以使用asyncio.create_subprocess_exec(…)
,它也会返回句柄,但其方法如wait()
都是协程。谢谢!Popen解决了阻塞问题。是的,我需要沟通。同时,我提出了一个单独的问题:。请注意,每个工人都必须与控制器进行通信,还必须通过数据流相互通信。因此,使用stdin/stdout的子流程可能不是解决问题的最佳方案。仍在研究和学习:-)欢迎任何建议!