Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a call to an executable from Python script?

Tags:

I need to execute this script from my Python script.

Is it possible? The script generate some outputs with some files being written. How do I access these files? I have tried with subprocess call function but without success.

fx@fx-ubuntu:~/Documents/projects/foo$ bin/bar -c somefile.xml -d text.txt -r aString -f anotherString >output 

The application "bar" also references to some libraries, it also create the file "bar.xml" besides the output. How do I get access to these files? Just by using open()?

Thank you,

Edit:

The error from Python runtime is only this line.

$ python foo.py bin/bar: bin/bar: cannot execute binary file 
like image 563
fx. Avatar asked Mar 18 '10 22:03

fx.


People also ask

How do I run a Python executable from Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

For executing the external program, do this:

import subprocess args = ("bin/bar", "-c", "somefile.xml", "-d", "text.txt", "-r", "aString", "-f", "anotherString") #Or just: #args = "bin/bar -c somefile.xml -d text.txt -r aString -f anotherString".split() popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait() output = popen.stdout.read() print output 

And yes, assuming your bin/bar program wrote some other assorted files to disk, you can open them as normal with open("path/to/output/file.txt"). Note that you don't need to rely on a subshell to redirect the output to a file on disk named "output" if you don't want to. I'm showing here how to directly read the output into your python program without going to disk in between.

like image 56
Peter Lyons Avatar answered Nov 12 '22 15:11

Peter Lyons


The simplest way is:

import os cmd = 'bin/bar --option --otheroption' os.system(cmd) # returns the exit status 

You access the files in the usual way, by using open().

If you need to do more complicated subprocess management then the subprocess module is the way to go.

like image 38
rz. Avatar answered Nov 12 '22 16:11

rz.