Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行C程序的Python脚本_Python_C++_C_Scripting - Fatal编程技术网

运行C程序的Python脚本

运行C程序的Python脚本,python,c++,c,scripting,Python,C++,C,Scripting,我有一个C/C++程序,它接受一组参数并向命令行显示一组输出(用于我的研究) 我想编写一个Python脚本,以针对不同的输入多次运行该程序,并将输出写入文件。我计划用详尽的输入运行程序 然而,我没有任何用Python编写脚本或编程的经验。所以,我想知道我是否可以从哪里开始 作为一个例子,我想写一个脚本来做: ./program -flag1 [val1] -flag2 [val2] -arg1 -arg2 -arg3 ... Append the output to Output.txt ./p

我有一个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通过终端执行命令。比如说

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

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

当前推荐的使用Python is子流程运行和控制可执行文件的方法。您可以使用不同的参数,捕获标准输出,处理它,或者只是重定向到任意文件。看看这里的文档

Python的子流程可能会很好地完成这个任务。话虽如此,像
bash
这样的工具可能更适合这个任务。什么平台?窗户?雨衣?Linux?“我有一个C/C++程序……”不,你没有。它是一个或另一个,除非你有一个C++程序,其中一个或多个编译单元在C中,并且你必须采取必要的小心使它们正常工作,这通常是不平凡的。