redirection of standard output of a Python command to a Python variable

TP Tribulations at Paralleles.invalid
Mon Oct 27 14:03:45 EDT 2008


Hi everybody,

I try to find a quick way to redirect the standard output of a Python
command (for example: print "message") to a python variable "foobar".
Ok, in this simple example, I could do foobar = "message", but in
fact 'print "message"' could be replaced by any Python function writing on
standard output.
I have googled on this subject.
To redirect to a variable, I could use a temporary file:

import sys
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print 'message'
sys.stdout = saveout
fsock.close()
fsock = open('out.log', 'r')
foobar = fsock.read()
fsock.close()
print "foobar= ", foobar

To redirect a system standard output directly to a variable (without
temporary file), I could do:

import os
f = os.popen("ls")
print f.read()
f.close()

But, how can I get the standard output of a Python command (print "message")
directly into a variable?

Thanks

Julien

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)



More information about the Python-list mailing list