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

主宰稳场 提交于 2019-11-28 21:16:01

EDIT FEB 21st, 2019: Problem Fixed

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:

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

Instead, you must add task to the current loop:

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

A simple example running on Jupyter Notebook:

This is no longer an issue in the latest jupyter release!

https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7

Just write an async function, and then await it directly in a jupyter cell.

async def fn():
  print('hello')
  await asyncio.sleep(1)
  print('world')

await fn()

I recently ran into the issue of not being able to run asyncio code in a Jupyter notebook. The issue is discussed here: https://github.com/jupyter/notebook/issues/3397

I tried one of the solutions in the discussion and it solved the issue so far.

pip3 install tornado==4.5.3

This replaced tornado version 5.x that was installed by default.

The asyncio code in a Jupyter notebook then ran as expected.

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.

Originally from here, but the example was not clear for me at first: https://realpython.com/async-io-python/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!