[Tutor] Difference between popens

Dave Kuhlman dkuhlman at rexx.com
Fri Jun 9 23:26:52 CEST 2006

On Fri, Jun 09, 2006 at 03:38:58PM -0400, Bernard Lebel wrote:
> Hi,
> I'd like to know what are the differences at the various os.popenX
> flavors. I read the documentation and I can see they return file
> objects..... so what can you do with these file objects? I mean, why
> would you need a set of file objects rather than another?

See documentation at

And, notice how the return values from the various versions of
popen are different file types: stdin, stdout, and stderr.

A summary:

- popen() gives you either an input pipe (stdin) or an output
  pipe (stdout) but not both.

- popen2() gives you both an input pipe (stdin) and output pipe

- popen3() gives you an input pipe (stdin) and output pipe
  (stdout) and an error pipe (stderr).

- popen4() gives you an input pipe and a pipe that combines output
  and errors (stdout and stderr).

Specifically, if you want to run a command, just like you would
with os.system(), but:

1. You want to *either* feed (pipe) text to your command *or* read
   results from your command, use os.popen() and use mode= 'w' or

2. You want to both feed (pipe) text to your command *and* read
   results from your command, use os.popen2().


If you get an input pipe, you should write text to that pipe, then
close that stream.  Doing close() is what triggers execution of the

If you get an output pipe, then (after the command runs), read
from that pipe to get the results of your command (i.e. the text
that the command wrote to stdout).

Here is a simple example that uses popen2::

    import os

    def test():
        instream, outstream = os.popen2('grep dave')
        instream.write('Line #1\n')
        instream.write('Line #2 dave is here\n')
        instream.write('Line #3\n')
        instream.write('Line #4 dave is also here\n')
        instream.write('Line #5\n')
        for line in outstream:
            print 'Line: %s' % line.rstrip()


Note that there is also a popen module, which has functions with
the same names and functionality:

    "This functionality is also available in the popen2 module
    using functions of the same names, but the return values of
    those functions have a different order."

See: http://docs.python.org/lib/module-popen2.html

Hope this helps.


Dave Kuhlman

More information about the Tutor mailing list