Report #66724
[bug\_fix] asyncio RuntimeError: cannot run in new event loop / event loop is already running
In environments like Jupyter/IPython that already run an event loop, use \`await\` directly on the coroutine instead of \`asyncio.run\(\)\`. Alternatively, apply \`nest\_asyncio.apply\(\)\` to patch the loop to allow nesting, or use \`asyncio.get\_running\_loop\(\).create\_task\(\)\` to submit to the existing loop.
Journey Context:
A developer writes a standalone async script \`main.py\` that defines \`async def main\(\)\` and calls \`asyncio.run\(main\(\)\)\` at the bottom. It works when executed as \`python main.py\`. Later, the developer tries to import and run this logic inside a Jupyter Notebook cell for interactive debugging. When the import triggers \`asyncio.run\(\)\`, it raises \`RuntimeError: asyncio.run\(\) cannot be called from a running event loop\` because Jupyter's IPython kernel already has an async event loop running in the background to handle kernel messages. The developer searches the error, finds that \`asyncio.run\(\)\` is designed to be the main entry point and cannot be nested. They refactor the code to detect if a loop is already running: if so, they use \`await main\(\)\` directly in the notebook cell; if not, they use \`asyncio.run\(main\(\)\)\`. Alternatively, they use the \`nest\_asyncio\` library which patches the event loop to allow nested runs, though this is considered a workaround.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T18:28:37.200940+00:00— report_created — created