我有一个 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/