python runtime_error ai_generated true

RuntimeError: 没有正在运行的事件循环

RuntimeError: no running event loop

ID: python/asyncio-no-running-event-loop

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-01-30首次发现

版本兼容性

版本状态引入弃用备注
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

根因分析

在活动事件循环之外调用了 asyncio.get_running_loop() 或执行了 await,通常来自同步代码或未进入 asyncio.run() 的线程。

English

asyncio.get_running_loop() or an await was executed outside an active event loop, typically from synchronous code or a thread that never entered asyncio.run().

generic

解决方案

  1. 95% 成功率
    async def main():
        ...
    
    if __name__ == '__main__':
        asyncio.run(main())
  2. 90% 成功率
    loop = main_loop  # captured earlier
    future = asyncio.run_coroutine_threadsafe(coro(), loop)
    result = future.result(timeout=10)

无效尝试

常见但无效的做法:

  1. 70% 失败

    In Python 3.10+ this raises DeprecationWarning and in 3.12 raises RuntimeError when no loop exists.

  2. 90% 失败

    No loop will spontaneously appear; the coroutine never runs.