6

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.

agf
  • 171,228
  • 44
  • 289
  • 238
Sagar
  • 73
  • 1
  • 1
  • 3
  • 1
    Try this question: http://stackoverflow.com/questions/2919783/python-calling-a-non-python-program-from-python – TorelTwiddler Sep 29 '11 at 23:57
  • @TorelTwiddler that's not what he wants to do -- that answer just returns the return code, not the output of the program. – agf Sep 30 '11 at 00:02
  • The correct duplicate is [What's a good equivalent to python's subprocess.check_call that returns the contents of stdout?](http://stackoverflow.com/questions/2924310/whats-a-good-equivalent-to-pythons-subprocess-check-call-that-returns-the-conte) – agf Sep 30 '11 at 00:03

2 Answers2

5

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.

agf
  • 171,228
  • 44
  • 289
  • 238
2

You can use the subprocess module for that.

result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
icktoofay
  • 126,289
  • 21
  • 250
  • 231