‘subprocess’ is a new addition (Python 2.4), and it provides a convenient and powerful way to run system commands. (...and you should use it instead of os.system, commands.getstatusoutput, or any of the Popen modules).
Unfortunately subprocess is a bit hard to use at the moment; I’m hoping to help fix that for Python 2.6, but in the meantime here are some basic commands.
Let’s just try running a system command and retrieving the output:
>>> import subprocess
>>> p = subprocess.Popen(['/bin/echo', 'hello, world'], stdout=subprocess.PIPE)
>>> (stdout, stderr) = p.communicate()
>>> print stdout,
hello, world
What’s going on is that we’re starting a subprocess (running ‘/bin/echo hello, world’) and then asking for all of the output aggregated together.
We could, for short strings, read directly from p.stdout (which is a file handle):
>>> p = subprocess.Popen(['/bin/echo', 'hello, world'], stdout=subprocess.PIPE)
>>> print p.stdout.read(),
hello, world
but you could run into trouble here if the command returns a lot of data; you should use communicate to get the output instead.
Let’s do something a bit more complicated, just to show you that it’s possible: we’re going to write to ‘cat’ (which is basically an echo chamber):
>>> from subprocess import PIPE
>>> p = subprocess.Popen(["/bin/cat"], stdin=PIPE, stdout=PIPE)
>>> (stdout, stderr) = p.communicate('hello, world')
>>> print stdout,
hello, world
There are a number of more complicated things you can do with subprocess – like interact with the stdin and stdout of other processes – but they are fraught with peril.