{"record":{"id":"38c56bd6fe102f9c","repo":"python/cpython","slug":"asyncio-run-cannot-be-called-from-a-running-even","errorCode":null,"errorMessage":"asyncio.run() cannot be called from a running event loop","messagePattern":"asyncio\\.run\\(\\) cannot be called from a running event loop","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"Lib/asyncio/runners.py","lineNumber":201,"sourceCode":"    This function always creates a new event loop and closes it at the end.\n    It should be used as a main entry point for asyncio programs, and should\n    ideally only be called once.\n\n    The executor is given a timeout duration of 5 minutes to shutdown.\n    If the executor hasn't finished within that duration, a warning is\n    emitted and the executor is closed.\n\n    Example:\n\n        async def main():\n            await asyncio.sleep(1)\n            print('hello')\n\n        asyncio.run(main())\n    \"\"\"\n    if events._get_running_loop() is not None:\n        # fail fast with short traceback\n        raise RuntimeError(\n            \"asyncio.run() cannot be called from a running event loop\")\n\n    with Runner(debug=debug, loop_factory=loop_factory) as runner:\n        return runner.run(main)\n\n\ndef _cancel_all_tasks(loop):\n    to_cancel = tasks.all_tasks(loop)\n    if not to_cancel:\n        return\n\n    for task in to_cancel:\n        task.cancel()\n\n    loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))\n\n    for task in to_cancel:\n        if task.cancelled():","sourceCodeStart":183,"sourceCodeEnd":219,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/asyncio/runners.py#L183-L219","documentation":"Error \"asyncio.run() cannot be called from a running event loop\" thrown in python/cpython.","triggerScenarios":"Raised when asyncio.run() is called from within a running event loop.","commonSituations":"See trigger scenarios.","solutions":["Do not call asyncio.run() inside async code; await the coroutine directly.","If running in an environment with an existing loop (e.g. Jupyter), use 'await main()' instead of asyncio.run(main())."],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}