Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call external program from python and get its output

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.

like image 824
Sagar Avatar asked Sep 29 '11 23:09

Sagar


People also ask

How do you get the output code in Python?

Python Output Using print() function We use the print() function to output data to the standard output device (screen). We can also output data to a file, but this will be discussed later.

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

How do you execute a shell command in Python and get output?

Get output from shell command using subprocessLaunch the shell command that we want to execute using subprocess. Popen function. The arguments to this command is the shell command as a list and specify output and error. The output from subprocess.


2 Answers

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.

like image 51
agf Avatar answered Sep 30 '22 10:09

agf


You can use the subprocess module for that.

result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
like image 27
icktoofay Avatar answered Sep 30 '22 11:09

icktoofay