运行C程序的Python脚本

2024-06-28 19:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: theto程序txt脚本outputprogramsubprocess
2条回答

我不确定这是否是您想要的,但是您可以使用python通过终端执行命令。例如

import os
os.system("echo 'hello world'")

这将执行终端命令>> echo 'hello world'

当前推荐的使用Python运行和控制可执行文件的方法是子流程模块。您可以使用不同的参数、捕获stdout、处理它,或者直接重定向到任意文件。看看这里的文档https://docs.python.org/3.2/library/subprocess.html#module-subprocess

相关问题 更多 >