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

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 20 Sep 2001 16:39:08 -0700 (PDT)


On Thu, 20 Sep 2001, Leona Euler wrote:

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


Hmmm... I can't think of one offhand.  This wrapper looks good.  If we
want it to work on functions that can take multiple arguments, we can
generalize funcwrap() like this:

###
def funcwrap(foo, *args, **kwargs):
    import sys, StringIO
    saved_stdout = sys.stdout
    sbuf = StringIO.StringIO()
    sys.stdout = sbuf
    foo(*args, **kwargs)
    result = sbuf.getvalue() 
    sys.stdout = saved_stdout
    sbuf.close()
    return result
###