caputering IO in python

David Bolen db3l at fitlinxx.com
Wed Aug 16 23:18:57 EDT 2000


Curtis Jensen <cjensen at bioeng.ucsd.edu> writes:

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

You can point sys.stdout to any object that you like that supports a
write() method, and it will receive any output that is normally
generated to stdout (either via the 'print' statement or directly via
the sys.stdout object, such as sys.stdout.write()).

The replacement object can do anything it would like with the data it
is being fed.  If all you want to do is hold onto all the output and
eventually treat it as a string, you could opt to just use the
[c]StringIO module directly.

For example:

    import sys
    import cStringIO

    old_stdout = sys.stdout
    sys.stdout = cStringIO.StringIO()

    # Import or run old module here

    results = sys.stdout.getvalue()
    sys.stdout = old_stdout

    # Here, results is a string with any data output by the module
    # If you were to do 'sys.stdout.write(results)' you would duplicate
    # the precise output that your old module would have generated

Note that if you do implement your own object to handle the I/O, you
should realize that when it comes to the 'print' statement, your
write() method isn't necessarily going to see the data in one shot.
For example, a command such as:

    print 'This', 'is', 'a', 'test'

will probably show up as five individual calls to your object, with
the last being for the newline.  That's not generally something you
need to worry about if you're just appending to a buffer, but if you
are trying to reroute the output on a line by line basis (say with a
prefix), then you have to pay attention to when an actual new line
begins.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list