Skip to content
Advertisement

“asyncio.run() cannot be called from a running event loop” when using Jupyter Notebook

I would like to use asyncio to get webpage html.

I run the following code in jupyter notebook:

JavaScript

However, it returns RuntimeError: asyncio.run() cannot be called from a running event loop

What is the problem?

How to solve it?

Advertisement

Answer

The asyncio.run() documentation says:

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

In your case, jupyter (IPython ≥ 7.0) is already running an event loop:

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.

Therefore you don’t need to start the event loop yourself and can instead call await main(url) directly, even if your code lies outside any asynchronous function.

Jupyter (IPython ≥ 7.0)

JavaScript

Python ≥ 3.7 and IPython < 7.0

JavaScript

In your code that would give:

JavaScript

Caution

There is a slight difference on how Jupyter uses the loop compared to IPython.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement