Runtime Error
RuntimeError: Event loop is closed while an asynchronous task is still pending
What This Error Means
This error occurs when a Python async function or coroutine is still running when the event loop is closed, typically when a program exits or an exception is raised.
Why It Happens
This error happens when an asynchronous task is not properly awaited, or the event loop is not properly managed, leading to the event loop being closed before the task completes.
How to Fix It
- 1To fix this error, make sure to await all asynchronous tasks before closing the event loop. You can also use try/except blocks to catch any exceptions and properly clean up the event loop.
Example Code Solution
async def my_task():
while True:
print('Running...')
async def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(my_task())
# Close the event loop without awaiting my_task()async def my_task():
try:
while True:
print('Running...')
finally:
# Clean up the task
pass
async def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(my_task())
await asyncio.gather(my_task())
# Close the event loop after awaiting my_task()Fix for RuntimeError: Event loop is closed while an asynchronous task is still pending
Browse Related Clusters
Related PYTHON Errors
RuntimeError: Cannot schedule new futures after shutdown
OperationalError: (1048, "Column 'username' cannot be null")
CursorError: LastError: (1062, "Duplicate entry 'user123' for key 'use
CursorError: unsupported database type: 'sqlite3': 'DBM' mode not supp
Related PYTHON Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error