用于运行 C 程序的 Python 脚本

标签 python c++ c scripting

我有一个 C/C++ 程序,它接受一组参数并向命令行显示一组输出(用于我的研究)。

我想编写一个Python脚本来针对不同的输入多次运行该程序并将输出写入文件。我计划使用详尽的输入来运行该程序。

但是,我没有任何用 Python 编写脚本或编程的经验。所以,我想知道是否可以获得一些从哪里开始的指导。

举个例子,我想编写一个脚本来执行以下操作:

./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg3 ...
Append the output to Output.txt
./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg4 ...
Append the output to Output.txt
./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg5 ...
Append the output to Output.txt
...
...
./program -flag1 [val1] -flag2 [val2] -arg1000 -arg1000 -arg1000 ...
Append the output to Output.txt

编辑:我通过命令行 bash 在 Linux 上运行该程序。

EDIT2 SLN:仅供将来可能是初学者做类似事情的人引用,解决方案如下所示。我剥离了所有只影响我的情况的部分。

import subprocess
from subprocess import Popen, PIPE

for commands in listArgs:

    # Build command through for loop in listArgs.
    # Details are omitted.
    cmd = ["./program", "-flag1", "val1", "-flag2", "val2", "-arg1", "-arg2", ... ]

    # Open/Create the output file
    outFile = open('/path/to/file/Output.txt', 'a+')

    result = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    out = result.stdout.read()

    outFile.write(out)
    outFile.close()

最佳答案

当前使用 Python 运行和控制可执行文件的推荐方法是 subprocess 模块。您可以使用不同的参数,捕获标准输出,对其进行处理,或者只是重定向到任意文件。看看这里的文档 https://docs.python.org/3.2/library/subprocess.html#module-subprocess

关于用于运行 C 程序的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990194/

相关文章:

python - WordNet - n 和数字代表什么?

python - 如何让键绑定(bind)在 pygame 中工作?

python - 一行列表中的平方和?

c++ - gcc 编译错误,在 Visual Studio 2008 C++ 中工作正常

c - 运行固件需要引导加载程序吗?

c - 在 gcc 中初始化数组,未定义对 `memcpy' 的引用

python - 访问 Bokeh 服务器 URL

c++ - 在期望 "char"的同时获取 "const char"

c++ - 将 Qt 程序与第三方程序连接起来——如何在它们之间发送信息?

C 从文件中读取 X 个字节,如果需要则填充