asyncio:RuntimeError此事件循环已在运行

问题描述 投票:2回答:1

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

但在我的情况下,我只启动一次事件循环,至少就我所见。此示例也直接遵循here指令:

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

并且结果变量保持不确定。

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

python async-await python-asyncio
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.