Report #104556
[bug\_fix] RuntimeError: Cannot close a running event loop
Use the \`nest\_asyncio\` package by calling \`nest\_asyncio.apply\(\)\` before running asyncio code in Jupyter. Alternatively, restart the Jupyter kernel and avoid running asyncio code that modifies the loop after the kernel's event loop has started.
Journey Context:
A developer was writing asynchronous Python code in a Jupyter notebook. They defined an async function and used \`asyncio.run\(\)\` inside a cell. The first execution succeeded, but the second execution raised \`RuntimeError: Cannot close a running event loop\`. This happened because \`asyncio.run\(\)\` tries to create and close a new event loop each time, but Jupyter already has a running event loop for the kernel. The developer initially tried to manually manage the loop with \`loop.close\(\)\` but that caused further errors. After finding the \`nest\_asyncio\` package, they learned that it patches asyncio to allow nested event loops. The fix works by allowing \`asyncio.run\(\)\` to be called within an already-running loop without closing it improperly. The root cause is that Jupyter's IPython kernel runs its own event loop, and standard asyncio functions are not designed to be used inside that loop.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-09-06T20:05:03.102470+00:00— report_created — created