Alice
Alice

Reputation: 1400

Jupyter notebook to run await function

Upon learning Coroutines and Tasks on Jupyter notebook ,

Run the following codes

import asyncio
async def main():
    print('learn')
    await asyncio.sleep(1)
    print('Jupyter')

enter image description here

However, it works properly on Ipython

enter image description here

Upvotes: 4

Views: 3014

Answers (1)

pylang
pylang

Reputation: 44545

This is a known issue with later versions of Jupyter. Install nest_asyncio as a workaround.

> pip install nest_asyncio

Code

import asyncio

import nest_asyncio


nest_asyncio.apply()


async def main():
    print("Learn")
    await asyncio.sleep(1)
    print("Jupyter")


asyncio.run(main())
# 'Learn'
# 'Jupyter'

TLDR; Running asyncio in notebooks conflicts with the existing event loop run by Tornado 5.0 in the background. A second option is to downgrade notebook to a version that depends on an older version of Tornado.

Upvotes: 8

Related Questions