目录

在Jupyter中执行asyncio代码

问题

在 Jupyter 中,如果执行 asyncio 的代码,例如

1
2
3
4
5
6
7
8
9
from requests_html import AsyncHTMLSession

session = AsyncHTMLSession()

async def get_google():
    r = await session.get('https://google.com/')
    return r

session.run(get_google)

会报错:

1
RuntimeError: This event loop is already running

解决

具体原因是因为 asyncio 不允许嵌套事件循环,而在 Jupyter 中就已经运行了一个时间循环。

一种解决方案是使用开发者 erdewit 开发的 nest_asyncio 模块,在 Jupyter 文件中添加并执行如下 cell 内容:

1
!pip install nest_asyncio
1
2
import nest_asyncio
nest_asyncio.apply()

参考