You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现exe启动检测无需等待进程终止的问题排查

问题根因
  • 执行阻塞:代码中调用的p.wait()方法会强制脚本等待当前exe进程结束后才会继续向下执行,这是你不手动关闭exe、脚本就不会处理后续文件的核心原因
  • 判定逻辑错误:你通过进程退出码result == 1判断启动成功的逻辑完全不符合需求,首先不同exe的退出码由其自身逻辑决定没有统一标准,其次你需要的是启动成功即判定成功,根本不需要等待进程结束获取退出码。只要subprocess.Popen执行时没有抛出异常,就代表exe进程已经成功拉起。
修正后代码
import glob
import subprocess

total = len(glob.glob("*.exe"))
notopened = 0
opened = 0
current = 0
print("opening exe's")
for fn in glob.glob("*.exe"):
    current += 1
    try:
        # 仅启动进程,不等待执行结束
        p = subprocess.Popen([fn])
        # 无异常即代表启动成功
        opened += 1
        num_prefix = "0" if current < 10 else ""
        print(f"[{num_prefix}{current}/{total}] {fn} opened [{round(opened / total * 100, 2)}%]")
    except Exception:
        notopened += 1
        num_prefix = "0" if current < 10 else ""
        print(f"[{num_prefix}{current}/{total}] {fn}   Unable to open [{round(opened / total * 100, 2)}%]")
补充说明
  • 修正后的代码只要成功启动进程就会立刻输出成功提示,同时继续处理下一个exe,完全符合你的预期
  • 如果你后续需要统一管理启动的进程,可以把所有返回的p对象存入列表,需要时可以批量调用p.terminate()关闭进程,避免后台残留
  • 代码中调整了百分比计算逻辑为已成功启动的exe占总数量的比例,如果需要其他统计逻辑可以自行修改计算规则

内容的提问来源于stack exchange,提问作者kid programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 00:15:04