asyncio.run() cannot be called from a running event loop问题解决

@[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()调用即可

链接: 原文.

你可能感兴趣的:(编程日常报错)