pythonjupyter-notebookruntime-errorpython-asyncio

asyncio.run() raise "RuntimeError: Event loop is closed" in a Jupyter Notebook


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?


Solution

  • 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.