python runtime_error ai_generated true

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

RuntimeError: Cannot create subprocess in event loop that is not running

ID: python/asyncio-cannot-create-subprocess

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

版本兼容性

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

根因分析

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

English

Attempting to create an asyncio subprocess (e.g., via asyncio.create_subprocess_exec) before the event loop is started or after it is stopped.

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. Using asyncio.get_event_loop() to get a loop and then calling run_until_complete 60% 失败

    get_event_loop() may return a closed loop; subprocess creation requires a running loop.

  2. Setting the event loop policy to WindowsProactorEventLoopPolicy 40% 失败

    This only applies to Windows; the error is about loop state, not platform.