首页 > 解决方案 > asyncio: RuntimeError 这个事件循环已经在运行

问题描述

这似乎是一个常见问题,例如:RuntimeError: This event loop is already running in python

但就我而言,至少在我所见的情况下,我只启动了一次事件循环。此示例也直接遵循此处的说明:

import asyncio

loop = asyncio.get_event_loop()

async def coroutine():
    print("hey")
    await asyncio.sleep(1)
    print("ho")
    return 1


async def main():

    tasks = []
    for i in range(2):
        tasks.append(asyncio.ensure_future(coroutine()))
    await asyncio.gather(*tasks)

results = loop.run_until_complete(main())
loop.close()

这将打印一条错误消息,并在协程中调用 print() 的输出:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-1-f4a74fbfac46> in <module>
     16     await asyncio.gather(*tasks)
     17 
---> 18 results = loop.run_until_complete(asyncio.gather(*tasks))
     19 loop.close()

~/anaconda3/envs/keras_dev/lib/python3.6/asyncio/base_events.py in run_until_complete(self, future)
    453         future.add_done_callback(_run_until_complete_cb)
    454         try:
--> 455             self.run_forever()
    456         except:
    457             if new_task and future.done() and not future.cancelled():

~/anaconda3/envs/keras_dev/lib/python3.6/asyncio/base_events.py in run_forever(self)
    407         self._check_closed()
    408         if self.is_running():
--> 409             raise RuntimeError('This event loop is already running')
    410         if events._get_running_loop() is not None:
    411             raise RuntimeError(

RuntimeError: This event loop is already running
hey
hey
ho
ho

结果变量保持未定义。

如何启动协程列表并正确收集它们的输出?

标签: pythonasync-awaitpython-asyncio

解决方案


在进行一些升级后,我也遇到了这个问题。事实证明,tornado包裹很可能是罪魁祸首。如果您tornado>=5.0在笔记本中运行事件循环会导致冲突。这里有详细的讨论,但目前的解决方案是使用pip install tornado==4.5.3.


推荐阅读