小编典典

异步:RuntimeError此事件循环已在运行

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

结果变量保持未定义状态。

我该如何启动协程列表并正确收集其输出?


阅读 219

收藏
2021-01-20

共1个答案

小编典典

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

2021-01-20