Setting stdout encoding
Ryan Ginstrom
software at ginstrom.com
Fri Sep 14 01:27:46 EDT 2007
> On Behalf Of Gabriel Genellina
> You should check that obj is an unicode object before calling
> encode.
> Strings should not be encoded.
...
> __getattr__ is only called when the attribute has NOT been
> found in the usual way, so checking for "write" is
> unnecesary. Just return getattr(self.stdout, attr) always.
Thanks a lot. Here is my modified class:
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 stream's 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)
Regards,
Ryan Ginstrom
More information about the Python-list
mailing list