0

I'm trying to run an async function inside a Jupyter Notebook using asyncio.run() like this:

import asyncio

async def my_task():
    await asyncio.sleep(1)
    return "Done"

asyncio.run(my_task())

But I get this error:

RuntimeError: Event loop is closed

I understand Jupyter uses an existing event loop, but what's the correct way to run async functions inside a notebook without this error?

Also:

Why does this work in a regular .py script but not in Jupyter?
Should I use nest_asyncio, await, or some other workaround?

1
  • I tested await my_task() and it works for me - so I solved problem in few second instead of wating few hours for answer ;) Commented Aug 7 at 11:17

1 Answer 1

3

Instead of using asyncio.run(), just use await directly in the notebook cell:


import asyncio

async def my_task():
    await asyncio.sleep(1)
    return "Done"

await my_task()

In Jupyter, there is already an event loop running. Since you can’t run a new event loop when one is already running, you get this error.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Happy to help! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.