[Tutor] capturing 'print'ed output and manipulating it

Leona Euler gyromagnetic@excite.com
Thu, 20 Sep 2001 03:59:54 -0700 (PDT)


Hi,
I'm calling a function written by someone else. This function basically
produces its output through a series of 'print' statements. I would like to
capture this output and manipulate it. To this end, I have written a wrapper
function that redirects stdout coming from the function into a StringIO
object like so:

def funcwrap(foo, arg):
    import sys, StringIO
    saved_stdout = sys.stdout
    sbuf = StringIO.StringIO()
    sys.stdout = sbuf                   # redirect stdout to the stringio
object
    foo(arg)                            # call function. output should now
go into sbuf
    result = sbuf.getvalue() 
    sys.stdout = saved_stdout           # clean up
    sbuf.close()
    return result

Is there a more efficient or direct way to do this?

Thanks.

-Brad





_______________________________________________________
http://inbox.excite.com