# RuntimeError: 线程 'MainThread' 中没有当前事件循环。

- **ID:** `python/asyncio-event-loop-is-running-pytest`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

自 Python 3.10 起，在没有运行循环的线程中调用 asyncio.get_event_loop() 不再隐式创建循环；依赖旧行为的代码会抛出此错误，常见于 pytest 和后台线程。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.10 | active | — | — |
| 3.11 | active | — | — |
| 3.12 | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.close()
   ```
2. **** (92% 成功率)
   ```
   # pytest.ini: asyncio_mode = auto
import pytest
@pytest.mark.asyncio
async def test_foo():
    assert await foo() == 1
   ```

## 无效尝试

- **** — Blocks upgrades and the behavior is slated for removal; not a durable fix. (70% 失败率)
- **** — Makes get_event_loop raise immediately; does not provide a usable loop. (85% 失败率)
