[Tutor] captering output of a cmd run using os.system.

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 1 Jun 2001 03:07:20 -0700 (PDT)


On Fri, 1 Jun 2001, Andrew Wilkins wrote:


> Let's say I have the following:
> 
> pipe = os.popen('python t','r')
> print pipe.read()
> 
> ############
> t.py should look like:
> 
> while 1:
>  x=raw_input('')
>  print x
> 
> How can I get the above to come up as visible? With popen it seems to
> work in the background.

> Is it possible to also collect input from stdin as well as the pipe?
> Say if I wanted to send a response to the raw_input bit through the
> pipe, or through the actual stdin...


Yes: you'll want to use the extended popen(): os.popen2().  It gives back
two file-like objects, one for input, and the other for output.  For
reference, let's look at the documentation:

"""
popen2(cmd[, bufsize[, mode]]) 
Executes cmd as a sub-process. Returns the file objects (child_stdin,
child_stdout). New in version 2.0. 
"""

    http://python.org/doc/current/lib/os-newstreams.html

Warning!  They switched the order of the arguments "bufsize" and "mode"
between os.popen() and os.popen2().  By default, though, it's in text
mode, so there's usually less of a need to tell Python to override the
defaults.


What we can do, then, might look something like this:

###
input_pipe, output_pipe = os.popen2('python t')
input_pipe.write("Hello world, this is a test.\n")
print output_pipe.read()
###


I have not been able to test this on Windows though, so I'm not sure how
successful this will be... *grin* Try it out, and if you run into
problems, email us again.

Good luck!