Calling external program from within python

Michael Tobis mtobis at gmail.com
Fri Jul 25 12:23:38 EDT 2008


These answers are too elaborate and abstract for the question.

Emmanouil,

Here is a program "myprog" which takes input and writes output to a
file. It happens to be python but it could be anything.

#####
#!/usr/bin/env python
a = int(raw_input("enter thing 1 "))
b = int(raw_input("enter thing 2 "))
c = raw_input("enter output file name ")
f = open(c,"w")
f.write("answer is %s\n" % str(a + b))
f.close()
#####

Here is python code which runs that program

#####
import os

f = os.popen("/path/to/myprog","w")
f.write("3\n4\noutputname\n") #can also do three separate writes if
that is more convenient
f.close()
#####

For some reason os.popen is deprecated in favor of the more verbose
subprocess.Popen, but this will work for a while.

Here is an even simpler approach that will take you a long way. This
should be very easy to understand.

#####
import os

params = open("temp","w")
params.write("3\n")
params.write("4\n")
params.write("outputname2\n")
params.close()

os.system("/path/to/myprog < temp")
#####

If you want python to pick up the stdout of your program as well look
into popen2.

Try basing your solution on those and if you have any problems let us
know what they are. In most cases such as you describe these will
work.

mt




More information about the Python-list mailing list