# 运行时错误：无法在未运行的事件循环中创建子进程

- **ID:** `python/asyncio-cannot-create-subprocess`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在事件循环启动前或停止后尝试创建 asyncio 子进程（例如通过 asyncio.create_subprocess_exec）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |
| 3.10 | active | — | — |

## 解决方案

1. **Use asyncio.run() to automatically manage the event loop lifecycle** (95% 成功率)
   ```
   async def main(): proc = await asyncio.create_subprocess_exec('cmd'); asyncio.run(main())
   ```
2. **Ensure the loop is running before creating subprocess** (90% 成功率)
   ```
   loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop); loop.run_until_complete(create_subprocess())
   ```

## 无效尝试

- **Using asyncio.get_event_loop() to get a loop and then calling run_until_complete** — get_event_loop() may return a closed loop; subprocess creation requires a running loop. (60% 失败率)
- **Setting the event loop policy to WindowsProactorEventLoopPolicy** — This only applies to Windows; the error is about loop state, not platform. (40% 失败率)
