python runtime_error ai_generated true

运行时错误:任务 <Task pending> 获取了附加到不同循环的 Future <Future pending>

RuntimeError: Task <Task pending> got Future <Future pending> attached to a different loop

ID: python/asyncio-future-attached-to-loop

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

版本兼容性

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

根因分析

协程或任务等待了一个属于不同事件循环的 Future,通常是由于跨线程混合循环或在 asyncio.gather 中使用来自不同循环的任务。

English

A coroutine or task awaits a Future that belongs to a different event loop, often due to mixing loops across threads or using asyncio.gather with tasks from different loops.

generic

解决方案

  1. 90% 成功率 Ensure all coroutines and futures are created in the same event loop
    loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop); loop.run_until_complete(main())
  2. 95% 成功率 Use asyncio.run() to avoid loop conflicts entirely
    async def main(): await asyncio.gather(coro1(), coro2()); asyncio.run(main())

无效尝试

常见但无效的做法:

  1. Creating a new loop and setting it globally 60% 失败

    The Future is still attached to the original loop; global setting does not migrate it.

  2. Using asyncio.ensure_future instead of create_task 70% 失败

    ensure_future also attaches to the current loop; same issue.