close

How do I run Python asyncio code in a Jupyter notebook?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I run Python asyncio code in a Jupyter notebook in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I run Python asyncio code in a Jupyter notebook?

  1. How do I run Python asyncio code in a Jupyter notebook?

    Thus, for any asyncio functionality to run on Jupyter Notebook you cannot invoke a loop.run_until_complete(...), since the loop you will receive from asyncio.get_event_loop() will be active.

  2. run Python asyncio code in a Jupyter notebook

    Thus, for any asyncio functionality to run on Jupyter Notebook you cannot invoke a loop.run_until_complete(...), since the loop you will receive from asyncio.get_event_loop() will be active.

Method 1

This is no longer an issue on the latest version of Jupyter Notebook. Authors of Jupyter Notebook detailed the case here.

Answer below was the original response that was marked correct by the op.


This was posted quite a bit ago, but in case other people are looking for an explanation and solution to the problem of running asynchronous code inside Jupyter Notebook;

Jupyter’s Tornado 5.0 update bricked asyncio functionalities after the addition of its own asyncio event loop:

Running on shell.
Running on JupyterNotebook.

Thus, for any asyncio functionality to run on Jupyter Notebook you cannot invoke a loop.run_until_complete(...), since the loop you will receive from asyncio.get_event_loop() will be active.

Instead, you must either add the task to the current event loop:

import asyncio
loop = asyncio.get_event_loop()
loop.create_task(some_async_function())

Or get the results via run_coroutine_threadsafe:

import asyncio
loop = asyncio.get_event_loop()
asyncio.run_coroutine_threadsafe(some_async_function(), loop)

Method 2

My aha moment with Asyncio in Jupyter looks like this:

import time,asyncio

async def count():
    print("count one")
    await asyncio.sleep(1)
    print("count four")

async def count_further():
    print("count two")
    await asyncio.sleep(1)
    print("count five")

async def count_even_further():
    print("count three")
    await asyncio.sleep(1)
    print("count six")

async def main():
    await asyncio.gather(count(), count_further(), count_even_further())

s = time.perf_counter()
await main()
elapsed = time.perf_counter() - s
print(f"Script executed in {elapsed:0.2f} seconds.")

Output:

count one
count two
count three
count four
count five
count six
Script executed in 1.00 seconds.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read