@[TOC](asyncio.run() cannot be called from a running event loop)

问题

在jupyter notebook中使用asyncio.run()时发生如上标题报错

解决方案

通过查找资料获得以下解决方案

The asyncio.run() documentation says:

This function cannot be called when another asyncio event loop is running in the same thread.

The problem in your case is that jupyter (IPython) is already running an event loop (for IPython ≥ 7.0):

You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races.

That’s the reason why you don’t need to start the event loop yourself in jupyter and you can directly call await main(url).

In jupyter

async def main():
    	print(1)
await main()

In plain Python (≥3.7)

import asyncio
async def main():
    print(1)
asyncio.run(main())

大致就是jupyter 已经运行了loop,无需自己激活,采用上文中的await()调用即可

链接: 原文.

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐