python runtime_error ai_generated true

DeprecationWarning: 没有当前事件循环

DeprecationWarning: There is no current event loop

ID: python/asyncio-loop-policy-deprecated

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

版本兼容性

版本状态引入弃用备注
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

在没有运行循环且当前线程未设置循环的情况下调用了 asyncio.get_event_loop();Python 3.10+ 弃用此行为,3.12+ 发出警告。

English

asyncio.get_event_loop() was called with no running loop and no loop set for the current thread; Python 3.10+ deprecates this behavior and 3.12+ warns.

generic

解决方案

  1. 95% 成功率
    Inside async code, use asyncio.get_running_loop():
    
    loop = asyncio.get_running_loop()
  2. 90% 成功率
    From sync code, use asyncio.new_event_loop() and manage lifetime explicitly:
    
    loop = asyncio.new_event_loop()
    try:
        loop.run_until_complete(coro())
    finally:
        loop.close()
  3. 92% 成功率
    Use asyncio.Runner (3.11+) for repeated runs:
    
    with asyncio.Runner() as runner:
        runner.run(coro())

无效尝试

常见但无效的做法:

  1. 70% 失败

    Hides the warning but the underlying API will be removed in 3.14.

  2. 65% 失败

    Creates a loop that is never closed; leaks resources and causes 'loop is closed' errors later.

  3. 90% 失败

    Not a maintainable fix; 3.9 is EOL in Oct 2025.