Wrapping stdout in a codec

Ryan Ginstrom software at ginstrom.com
Mon Oct 22 06:00:08 CEST 2007


> On Behalf Of JKPeck
> otherwise anonymous.  How can we accomplish this wrapping?  
> Our application may be loaded into a Python program that has 
> already set up stdout.

Do you mean something like this?

import sys

class OutStreamEncoder(object):
    """Wraps a stream with an encoder"""
    def __init__(self, outstream, encoding=None):
        self.out = outstream
        if not encoding:
            self.encoding = sys.getfilesystemencoding()
        else:
            self.encoding = encoding

    def write(self, obj):
        """Wraps the output stream, encoding Unicode
        strings with the specified encoding"""

        if isinstance(obj, unicode):
            self.out.write(obj.encode(self.encoding))
        else:
            self.out.write(obj)

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

You can wrap sys.stdout easily:
sys.stdout = OutStreamEncoder(sys.stdout)

The code, with unit tests:
http://www.ginstrom.com/code/streamencode.zip

Regards,
Ryan Ginstrom




More information about the Python-list mailing list