[Tutor] How to run a system application and get the stdout in Python?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 17 01:10:45 EST 2003

On Sun, 16 Nov 2003, Scott Chapman wrote:

> I want to run a system application on my web server (using Draco) and
> send the stdout of the system command (htmldoc) to the client's web
> browser.
> I see a number of os module possibilities to run system commands.
> Here's what I'm trying to run:
> /usr/bin/htmldoc -t pdf --webpage
> ''
> What's the best way to run this and how do I grab the stdout of the
> command?

Hi Scott,

(It's sorta funny how simliar questions come in streaks.  *grin*)

You'll want to look at os.popen(): it'll let you execute an external
command and grab its output as if it were a file-like object.  For

>>> import os
>>> os.popen("ls src/python")
<open file 'ls src/python', mode 'r' at 0x60320>
>>> f = os.popen("ls src/python")
>>> f.readline()
>>> f.readline()

There's another function called os.system() that does something similar:
it also executes external commands, but its return value is the
"errorlevel" of the command, and not its stdout.

If you're looking for more fine-grained control, there a module called
'popen2' that has more powerful process-opening functions:


but I think that, for the moment, os.popen() should do the trick.

Good luck to you!

More information about the Tutor mailing list