Setting stdout encoding

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Sep 14 00:23:52 EDT 2007


En Thu, 13 Sep 2007 08:43:11 -0300, Ryan Ginstrom <software at ginstrom.com>  
escribi�:

>> On Behalf Of Fabio Zadrozny
>> Makes sense... Do you think that creating a new object,
>> setting it as sys.stdout and overriding its write() method to
>> check for a unicode string to do
>> original_stdout.write(unicode_str.encode(my_encoding)) would
>> do it?
>
> Here's an output stream encoder I have used. It might be kind of  
> screwball,
> so I'd welcome any feedback on it, but it does work for encoding output
> streams.

Looks fine to me, just two comments:

>     def write(self, obj):
>         """Wraps the output stream's write method, encoding it with
>         the specified encoding"""
>
>         self.stdout.write(obj.encode(self.encoding))

You should check that obj is an unicode object before calling encode.  
Strings should not be encoded.

>     def __getattr__(self, attr):
>         """Delegate everything but write to the stream"""
>
>         if attr != "write":
>             return getattr(self.stdout, attr)
>         return self.write

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

-- 
Gabriel Genellina




More information about the Python-list mailing list