【问题标题】:Python Script to run a C Program [closed]运行 C 程序的 Python 脚本 [关闭]
【发布时间】:2015-03-15 10:13:17
【问题描述】:

我有一个 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 的子进程可能会做得很好。 . .话虽如此,像bash 这样的工具可能更适合这项任务。
  • 什么平台?视窗?苹果? Linux?
  • “我有一个 C/C++ 程序...”不,你没有。这是其中之一,除非您有一个 C++ 程序,其中一个或多个编译单元使用 C 语言,并且您已采取必要的措施使它们正常工作,这通常很重要。

标签: python c++ c scripting


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2021-01-27
      • 2011-03-16
      • 2021-07-22
      相关资源
      最近更新 更多