python - 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
结果变量保持未定义。
如何启动协程列表并正确收集它们的输出?
解决方案
在进行一些升级后,我也遇到了这个问题。事实证明,tornado
包裹很可能是罪魁祸首。如果您tornado>=5.0
在笔记本中运行事件循环会导致冲突。这里有详细的讨论,但目前的解决方案是使用pip install tornado==4.5.3
.
推荐阅读
- php - 存储和公共之间的 Laravel Symlink 不起作用?
- android - 从 1.0.2 到 1.1.0 的约束布局库更新出错 (Guideline.getAnchor)
- magento - 已弃用:__autoload() 已弃用,在 magento cd 1.9 上使用 spl_autoload_register()
- xml - XML 签名中 KeyInfo 的用途
- ios - 如何在swift4中的scrollView上设置admob
- mysql - 构造一对多表php mysql的正确方法
- r - 减少多个条形图R中条形的宽度
- html - 视觉和布局视口和文档
- asp.net-mvc - asp.net mvc 从视图中排除 Id
- html - 背景图像悬停转换延迟