每个Python进程的Asyncio事件循环(aioprocess,多个事件循环)

2022-03-25 00:00:00 python python-asyncio

问题描述

我有两个进程;一个主进程和子进程。主进程正在运行asyncio事件循环,并启动子进程。我想在子进程中启动另一个异步事件循环。我正在使用aioprocessing模块启动子进程。

子流程函数为:

def subprocess_code():
     loop = asyncio.get_event_loop()
     @asyncio.coroutine
     def f():
        for i in range(10):
            print(i)
            yield from asyncio.sleep(1)
     loop.run_until_complete(f())

但我收到一个错误:

    loop.run_until_complete(f())
  File "/usr/lib/python3.4/asyncio/base_events.py", line 271, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.4/asyncio/base_events.py", line 239, in run_forever
    raise RuntimeError('Event loop is running.')
RuntimeError: Event loop is running.
是否可以在子流程中启动新的或重新启动现有的asyncio事件循环?如果是,如何?


解决方案

抱歉打扰了! 我找到了一个解决方案!

policy = asyncio.get_event_loop_policy()
policy.set_event_loop(policy.new_event_loop())
loop = asyncio.get_event_loop()

将此代码放入带有异步事件循环的进程启动的子进程内,以启动新的asycnio事件循环

相关文章