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

链接: 原文.

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值