caputering IO in python

Alex Martelli alex at magenta.com
Thu Aug 17 05:44:36 EDT 2000


"Curtis Jensen" <cjensen at bioeng.ucsd.edu> wrote in message
news:399B3352.59857E8D at bioeng.ucsd.edu...
> I have a module that writes to standard out.  I would like to redirect
> that output to a python string, without modifing the module.  Is there a
> way I can call a module's function and trick it into writting to a
> string instead of standard out?  Thanks.

Yes, just import StringIO or cStringIO, and set sys.stdout to
an instance of the StringIO class defines in these library
modules.  All print statements will 'write' to the string-IO
object from that point onwards, including those executed in
other modules.  When you're done, the getvalue() method of
the above-mentioned StringIO instance will give you the string
with all output performed.

Example:
-- chatty.py
print "Hello, I'm chatty!"
print "and I write to stdout."

def afun():
    print "this function is chatty too"
-- capturout.py
import sys
import StringIO

def dowork():
    saveit = sys.stdout
    sys.stdout = StringIO.StringIO()

    import chatty
    chatty.afun()

    theoutput = sys.stdout.getvalue()
    sys.stdout = saveit

    print "I captured...:"
    print repr(theoutput)
    print "(that's all)"


Importing capturout and running capturout.dowork() will
produce:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import capturout
>>> capturout.dowork()
I captured...:
"Hello, I'm chatty!\012and I write to stdout.\012this function is chatty
too\012"
(that's all)
>>>


Alex






More information about the Python-list mailing list