用于运行 C 程序的 Python 脚本

Python Script to run a C Program

本文关键字:Python 脚本 程序 运行 用于      更新时间:2023-10-16

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

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

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 运行和控制可执行文件的方法是子进程模块。您可以使用不同的参数,捕获标准输出,处理它,或者只是重定向到任意文件。在此处查看文档 https://docs.python.org/3.2/library/subprocess.html#module-subprocess

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

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

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