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

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 1 Jun 2001 01:54:40 -0700 (PDT)


On Fri, 1 Jun 2001, GADGIL PRASAD     /INFRA/INFOTECH wrote:

> a cmd that I run using os.sustem() gives the output that I want to
> assign to a var and use later in prog. How do I do that ?

Ah, that's where you'll want to use os.popen().  It does pretty much the
same thing as os.system() --- it executes an external command from the
system.  The only difference is that it allows us to grab the output
directly.


For example, if we wanted to store the output of a 'dir' command, we can
do something like this:

###
# Small program to demonstrate os.popen().
import os

f = os.popen('dir')
output = f.read()

print "Here's what we got back:", output
###


What os.popen() does is return something that looks like a file: we can
read() from it in one sitting, or pull out lines at a time with
readline().  os.popen() is mentioned in the reference docs here:

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


If you're curious, you might want to see what sort of things we'd expect
files to do:

    http://python.org/doc/current/lib/bltin-file-objects.


Good luck!