Assigning output from a simple python statement

Michael Hudson mwh21 at cam.ac.uk
Thu Mar 16 10:56:58 CET 2000


"Wilson Fletcher" <wilson at mclachlan.com.au> 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
    try:
        exec code
    finally:
        sys.stdout = so
    sio.seek(0)
    return sio.read()

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.

Cheers,
M.

-- 
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