Assigning output from a simple python statement

Michael Hudson mwh21 at
Thu Mar 16 10:56:58 CET 2000

"Wilson Fletcher" <wilson at> writes:

> I would like to execute an unknown python statement and store the output.
> It will typically be a print statement. eg. "print 'Hello World'"
> I won't know the statement until runtime becuase it will come from a
> database. BUT I want to capture anything that goes to stdout and process
> it. 

try this:

import sys,StringIO

def capture_output(code):
    so = sys.stdout
    sio = StringIO.StringIO()
    sys.stdout = sio
        exec code
        sys.stdout = so

not tested, but should work.

I leave out my usual "do you really want to `exec' things you don't
know everything about" comment, I think.


very few people approach me in real life and insist on proving they are
drooling idiots.                         -- Erik Naggum, comp.lang.lisp

More information about the Python-list mailing list