Copy Stdout to string

Ryan Ginstrom software at ginstrom.com
Tue Apr 1 10:32:12 EDT 2008


> On Behalf Of sophie_newbie
> Hi, I'm wondering if its possible to copy all of stdout's 
> output to a string, while still being able to print on 
> screen. I know you can capture stdout, but I still need the 
> output to appear on the screen also...

If I understand you correctly, the following class should work.

from StringIO import StringIO

class OutBuffer(object):
    """Wraps a stream, and keeps output as a buffer
    
    Usage:
    >>> import sys
    >>> sys.stdout = OutBuffer(sys.stdout)
    >>> print "spam"
    spam
    >>> print "egg"
    egg
    >>> sys.stdout.getvalue().splitlines()
    ['spam', 'egg']
    """

    def __init__(self, outstream):
        self.out = outstream
        self.buffer = StringIO()

    def write(self, obj):
        """Writes obj to the output stream, storing it to a buffer as
well"""
        self.out.write(obj)
        self.buffer.write(obj)
        
    def getvalue(self):
        """Retrieves the buffer value"""
        return self.buffer.getvalue()

    def __getattr__(self, attr):
        """Delegate everything but write and getvalue to the stream"""
        return getattr(self.out, attr)

Regards,
Ryan Ginstrom




More information about the Python-list mailing list