Python: How do I redirect output of os.system to python shell?
Question: I want to make a simple batch script using python using os.system. I am able
to run the commands just fine, but the output for those commands dont print to
the python shell. Is there some way to redirect the output to the python
shell?


Answer: You can use
[`subprocess`](http://docs.python.org/library/subprocess.html#module-
subprocess).

    
    
    from subprocess import Popen, PIPE
    p1 = Popen(['ls'], stdout=PIPE)
    print p1.communicate()[0]
    

This will print the directory listing for the current directory. The
`communicate()` method returns a tuple `(stdoutdata, stderrdata)`. If you
don't include `stdout=PIPE` or `stderr=PIPE` in the `Popen` call, you'll just
get `None` back. (So in the above, `p1.communicate[1]` is `None`.)

In one line,

    
    
    print Popen([command], stdout=PIPE).communicate()[0]
    

prints the output of `command` to the console.

You should read more
[here.](http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-
backquote) There's lots more you can do with `Popen` and `PIPE`.

