Call external program from python and get its output(从 python 调用外部程序并获取其输出)
问题描述
我想从 Python 调用一个用 C++ 编写并编译的程序 (.exe
).可执行文件将两个文件作为输入并返回一个分数.
I want to call a program (.exe
), which is written in C++ and compiled, from Python. The executable takes as input two files and returns a score.
我需要为多个文件执行此操作.所以,我想在 python 中编写一个小脚本,循环多个文件,将它们传递给可执行文件并取回值.
I need to do this for multiple files. So, I would like to write a small script in python which loops over multiple files, passes them to the executable and gets back the values.
现在,我已经完成了搜索,我知道 SWIG 和 Boost::Python 可能是一个选择,但我试图找到是否有更简单的方法.我不需要扩展"C++ 程序.我只是想像从命令行一样调用它并获取返回的数字.
Now, I have done my search and I know about SWIG and Boost::Python may be an option but I was trying to find if there is an easier way. I do not need to 'extend' the C++ program. I simply want to call it just like I would from a command line and get the returned number.
推荐答案
要运行外部程序并获取其输出,请使用 subprocess.check_output
在 Python 2.7+ 上.文档中的示例:
To run an external program and get its output, use subprocess.check_output
on Python 2.7+. The example from the docs:
>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null
'
check_call
只是返回程序的返回码,而不是输出.
check_call
just returns the return code of the program, not the output.
这篇关于从 python 调用外部程序并获取其输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 python 调用外部程序并获取其输出


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 筛选NumPy数组 2022-01-01