[Tutor] assigning a variable

Jeff Shannon jeff at ccvcorp.com
Tue Oct 14 16:34:31 EDT 2003


Gerhard Venter wrote:

> I have the following:
> 
>  >>> import os
>  >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic 
> translate')
> 11
>  >>> print K
> 0
> 
> My question is why does K not assume the value of 11 and what can I do 
> to make it do so.

Not all output is return values.  In fact, the two are completely 
separate.  If you call a function from within the Python interpreter, 
and don't assign the return value to a variable, then Python will 
display it for you, and that's probably what's confusing you, but in 
this case they're two different things.

The os.system() function runs a system command, and then returns the 
exit value of that command.  Most system commands have exit values 
that indicate whether or not the command succeeded (and if it failed, 
some indication of why).  In this case, '0' is the exit value of the 
curl command, which indicates that curl ran successfully.

What you *want* to get, the 11, is the output of the command -- the 
shell's stdout.  Just like any *nix filter or redirection, stdout can 
be piped to different programs or what have you.  In this case, the 
stdout of curl is piped to grep, and the stdout from grep comes back 
to Python.  Python simply prints the stdout of os.system() calls to 
the screen.

If you want to be able to capture the stdout of your program, then you 
need to look into using  os.popen() and its related functions. 
os.popen() will return an open file-like object that is connected to 
the stdout of the system command; you can then use that object's 
read()/readlines() method(s) to assign that output to a Python variable.

Hope this helps!

Jeff Shannon
Technician/Programmer
Credit International





More information about the Tutor mailing list