Call an external program from python and get its output

I want to call a program ( .exe) that is written in C ++ and compiled from Python. The executable takes two files as input and returns the result.

I need to do this for multiple files. So, I would like to write a small script in python that iterates over several files, passes them to the executable, and returns the values.

Now I have done my search, and I know about SWIG and Boost :: Python may be an option, but I tried to find if there is an easier way. I do not need to "extend" the program in C ++. I just want to call it the same as on the command line and get the return number.

+5
source share
2 answers

To run an external program and get its output, use subprocess.check_outputPython 2.7+. 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 program return code, not the output.

+5
source

You can use the modulesubprocess for this.

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

All Articles