Welcome, guest | Sign In | My Account | Store | Cart

os.popen is really great when you need to drive a text based software. Here is a sample of use which create animated graphics using the free software gnuplot.

Python, 6 lines
import os
f=os.popen('gnuplot', 'w')
print >>f, "set yrange[-300:+300]"
for n in range(300):
	print >>f, "plot %i*cos(x)+%i*log(x+10)" % (n,150-n)

c.l.py don't mention very often the os.popen function. But it can be a very great tool when you want to use python as a glue language.

In this sample: The f=os.popen('gnuplot', 'w') create a file like object which is connected to the input (stdin) of the software launched (note that os.popen('gnuplot') would have open a file linked to the output (stdout)). After you only have to write into this file the same things that you would have written if you had used your software interactively.

The popen2 module give alternate functions that allow to access in the same time both to stdin, stdout and stderr (sample on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117221)


Tino Lange 21 years, 8 months ago  # | flag

gnuplot.py. Just have a look at: http://sourceforge.net/projects/gnuplot-py/ - there's quite a complex module already that works on the basis of your reciepe.

Noah Spurrier 21 years, 1 month ago  # | flag

Try Pexpect instead of popen when you want to use python as a glue language. Pexpect was designed just for this type of application. Popen has a lot of problems when working with interactive child applications. You application is safe because it does not try to read back any of the GNUPlot responses, but if you did want your script to depend on responses from the child, then a pipe will not work.

Try Pexpect here:

Created by Sébastien Keim on Fri, 18 Jan 2002 (PSF)
Python recipes (4591)
Sébastien Keim's recipes (24)

Required Modules

Other Information and Tasks