Call external program from python and get its output

给你一囗甜甜゛ 提交于 2019-12-18 05:04:20

问题


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.

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.

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.


回答1:


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\n'

check_call just returns the return code of the program, not the output.




回答2:


You can use the subprocess module for that.

result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])


来源:https://stackoverflow.com/questions/7604621/call-external-program-from-python-and-get-its-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!