我有两个过程;主进程和子进程。主进程正在运行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
事件循环?如果是这样,怎么样?
答案 0 :(得分:16)
对不起打扰! 我找到了解决方案!
policy = asyncio.get_event_loop_policy()
policy.set_event_loop(policy.new_event_loop())
loop = asyncio.get_event_loop()
把这段代码用asyncio事件循环从进程启动的子进程内启动新的asycnio事件循环