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

如何用Python subprocess循环调用test.exe批量处理姓名与文档查询?

用Python的subprocess批量调用test.exe处理多组姓名与文档

完全可以用Python的subprocess模块实现批量处理,核心思路就是通过嵌套循环遍历姓名列表和文档列表,逐个组合调用test.exe并捕获输出结果。

基础实现代码

import subprocess

# 定义需要处理的姓名列表和文档列表
names = ["Mike", "John", "Lisa", "Emma"]
documents = ["word.docx", "report.docx", "meeting_notes.docx"]

# 嵌套循环遍历所有组合
for name in names:
    for doc in documents:
        # 调用test.exe,传入姓名和文档作为命令行参数
        # 如果test.exe不在当前脚本目录,需替换为绝对路径,比如["C:/tools/test.exe", name, doc]
        process = subprocess.run(
            ["test.exe", name, doc],
            capture_output=True,
            text=True,
            check=False  # 设置为False避免执行出错时直接终止脚本,方便自定义错误处理
        )
        
        # 处理执行结果
        if process.returncode == 0:
            # 提取输出的次数(假设test.exe直接输出数字)
            occurrence_count = process.stdout.strip()
            print(f"{name} 在 {doc} 中的出现次数:{occurrence_count}")
        else:
            # 输出错误信息
            error_msg = process.stderr.strip() or "未知错误"
            print(f"处理 {name} 和 {doc} 失败:{error_msg}")

关键参数说明

  • capture_output=True:捕获程序的标准输出和错误输出,方便后续处理。
  • text=True:将输出结果转为字符串(而非字节流),无需手动解码。
  • check=False:如果test.exe执行返回非0的退出码,脚本不会直接抛出异常,而是通过returncode判断执行状态,适合批量处理时容错。

进阶错误处理(可选)

如果需要更严谨的错误捕获,可以用try-except包裹调用逻辑:

import subprocess

names = ["Mike", "John"]
documents = ["word.docx", "invalid_file.docx"]

for name in names:
    for doc in documents:
        try:
            process = subprocess.run(
                ["test.exe", name, doc],
                capture_output=True,
                text=True,
                check=True  # 执行出错时直接抛出CalledProcessError
            )
            print(f"{name} 在 {doc} 中的出现次数:{process.stdout.strip()}")
        except subprocess.CalledProcessError as e:
            print(f"处理 {name} - {doc} 出错:{e.stderr.strip()}")
        except FileNotFoundError:
            print("错误:未找到test.exe,请检查路径是否正确")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:08