Skip to content

How to Fix Python asyncio 'Event loop is closed' Error

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python asyncio 'Event loop is closed' Error. We cover key concepts, practical examples, and best practices.

The Problem

You see RuntimeError: Event loop is closed when running asyncio code, often after a previous loop was shut down or in environments like Jupyter that manage loops automatically. This commonly happens when calling asyncio.run() twice in a row or after manually closing a loop with loop.close().

Quick Fix

Use asyncio.run() Instead of Manual Loop Management

python3 -c "
import asyncio
async def main():
    await asyncio.sleep(1)
    return 'done'

result = asyncio.run(main())
print(result)
"
# done

asyncio.run() creates a new event loop, runs the coroutine, and closes the loop cleanly. It is the recommended way to run asyncio code from a synchronous context because it handles loop lifecycle automatically, avoiding stale-loop errors entirely.

Create a Fresh Loop When Needed

python3 -c "
import asyncio
async def say_hello():
    return 'hello'

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(say_hello())
print(result)
loop.close()
"
# hello

Use new_event_loop() and set_event_loop() when you need explicit control over the loop, such as in threaded applications where each thread needs its own loop. Always close the loop afterward to prevent resource leaks.

For Jupyter / Interactive Environments

python3 -c "
import nest_asyncio
nest_asyncio.apply()
"

The nest_asyncio package patches the event loop to allow nested usage. This is the standard fix in Jupyter notebooks where the kernel already manages an active event loop that cannot be replaced.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Debug with Loop Callback Tracing

python3 -c "
import asyncio
loop = asyncio.new_event_loop()
loop.set_debug(True)
print('Debug mode enabled')
"
# Debug mode enabled

Enable debug mode on the event loop with loop.set_debug(True). This logs callback execution times and identifies coroutines that take too long, helping you find the root cause of loop closure issues before they crash your application.

Prevention

  • Use asyncio.run() for top-level coroutines instead of manually creating and closing loops
  • In long-running applications, reuse the same event loop rather than creating new ones on each call
  • Install nest_asyncio when writing asyncio code in Jupyter or IPython environments
  • Avoid calling loop.close() unless you are certain no other code depends on that loop

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro