Re: Python Embedding: redirecting output

Guido.van.Rossum@cwi.nl
Wed, 08 Feb 1995 20:05:21 +0100

> I'm busy embedding Python into a distributed application environment
> and I need to gather up Python's normal and exceptional text output
> and return it to the application's front end as part of a command's
> return value. While driving from the top is easy with run_command(),
> gathering the output seems non-trivial. So far, my strongest candidate
> is to reimplement output on the standard sys.stderr and sys.stdout
> objects and to diddle run_command() to initiate and terminate
> result gathering. Have others done this and found better ways or
> have suggestions to give?

>From Python, this is simple; use something like

import StringIO
import sys
myout = StringIO.StringIO()
myerr = StringIO.StringIO()
saveout = sys.stdout
saveerr = sys.stderr
try:
sys.stdout = myout
sys.stderr = myerr
exec <whatever>
finally:
sys.stdout = saveerr
sys.stderr = saveerr

and then myout.getvalue() and myerr.getvalue() return the standard
output and standard error text from <whatever>.

Also note that if you want a standard exception traceback as well, you
could replace "exec <whatever>" by

try:
except <whatever>
except:
import traceback
traceback.print_exc()

(This prints the traceback on stdout -- redirecting it to stderr is
left as an excercise :-)

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>