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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Oct 27 19:45:43 CET 2008


En Mon, 27 Oct 2008 16:03:45 -0200, TP <Tribulations at paralleles.invalid>  
escribió:

> 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

You are close - but instead of using a real file, look at the StringIO  
module [1]

import sys
 from cStringIO import StringIO

old_stdout = sys.stdout
sys.stdout = stdout = StringIO()
print 'message'
sys.stdout = old_stdout
foobar = stdout.getvalue()
print "foobar= ", foobar

(In case you start playing with this and make a mistake, you can restore  
the original stdout from sys.__stdout__)

[1] http://docs.python.org/library/stringio.html

-- 
Gabriel Genellina




More information about the Python-list mailing list