[Pythonmac-SIG] How to print unicode to OS-X Terminal.app

Kent Johnson kent37 at tds.net
Fri Feb 15 04:00:28 CET 2008


Kent Johnson wrote:
> Christopher Barker wrote:
>> Robin Dunn wrote:
>>> Just replace sys.stdout with an object with a write() method that does 
>>> what you want.
>> I don't think that will do it, as "print" will have already converted 
>> the object to a string, and it does that with str(), which calls 
>> object.__str__, which used the default encoding....
> 
> That's what I thought, too, but a Q&D experiment seemed to work...

Here it is:

In [4]: s = u'\xe3'
In [5]: print s
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode 
character u'\xe3' in position 0: ordinal not in range(128)

In [6]: print s.encode('utf-8')
ã
In [7]: import sys
In [8]: class convert(object):
    ...:     def write(self, s):
    ...:         if isinstance(s, unicode):
    ...:             s = s.encode('utf-8')
    ...:         sys.__stdout__.write(s)
    ...:
    ...:
In [9]: sys.stdout = convert()
In [10]: print s
ã

I guess the conversion actually happens in sys.stdout.write(), not in print.

Kent


More information about the Pythonmac-SIG mailing list