[Tutor] (no subject)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 8 Mar 2001 12:48:26 -0800 (PST)


On Thu, 8 Mar 2001, Glen Bunting wrote:

> I have what I hope is a very easy question.  I need to save the
> results of a command to a variable but I am not sure how to go about
> doing it.  This is what I have done so far:
> 
> >>>import os
> >>>test  = os.system('cut --character=5- ActsAutomation,ihello,com')

The os.system() function returns the "errorlevel" of its command, which is
often different from its printed output.  (This errorlevel value is useful
when you're writing shell scripts that check for the success or failure of
a command.) That's where the zero is coming from.

What you'll want to use instead is os.popen(), which gives us a
"file"-like object.  From this, we can read off the program's output.

For example:

###
>>> import os
>>> output = os.popen('ls *.txt').read()
>>> print output
indrel.txt
list.txt
rules.txt
sentenceword.txt
###

will call the ls command, get the file, read() off all of its string
contents, and store that into our output.

If you have more questions, please feel free to ask us.