用于运行 C 程序的 Python 脚本
Python Script to run a C Program
我有一个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'
相关文章:
- 如何在c++中使用system()来运行包含空格的python脚本
- 如何将真正的字符串从python c-api转换为python脚本
- 在从Qt调用的Python脚本中导入OpenCV崩溃
- 使用 Main() 返回值作为 python 脚本的参数
- 如何制作启动 Python 脚本的 linux 后台进程(在 c 中)
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- C++ Python 并不总是执行 Python 脚本
- 从C++调用 Python 脚本以持续流式传输数据
- 将数据从 c++ 文件连续发送到 Python 脚本以进行进一步处理
- 错误,在嵌入在C++程序中的 python 脚本中使用 matplotlib 时
- 在使用PyInstaller冻结Python脚本时包含一个C++可执行文件
- 使用 pipe() 和 fdopen() 将数据从 Python 脚本传递到 Windows 中的C++应用程序
- Python 脚本到 c .obj 文件
- 从 c++ 运行 python 脚本时出现问题
- C++ :从C++脚本内部触发存储在我机器上的 python 脚本
- 从 c++ 中运行 python 脚本,找不到模块
- 参数从 Python 脚本传递到 C++ 使用 boost-python
- 无法从Linux,C ++执行"my_script" python脚本"main(filename)"功能;pModule = PyImport_Import(pName);返回空值
- 如何在C ++(qt)代码中使用python脚本?(网页抓取方面)
- 将对象从 python 脚本传递给 c++