Unicode conversion in 'print'

Ricardo Bugalho ricardo.b at zmail.pt
Thu Jan 13 11:24:00 EST 2005


Hello,
 I'm using Python 2.3.4 and I noticed that, when stdout is a terminal, the
'print' statement converts Unicode strings into the encoding defined by
the locales instead of the one returned by sys.getdefaultencoding().
However, I can't find any references to it. Anyone knows where it's
descrbed?

Example:

!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, locale

print 'Python encoding:', sys.getdefaultencoding()
print 'System encoding:', locale.getpreferredencoding()
print 'Test string: ', u'Olá mundo'


If stdout is a terminal, works fine
$ python x.py
Python encoding: ascii
System encoding: UTF-8
Test string:  Olá mundo

If I redirect the output to a file, raises an UnicodeEncodeError exception
$ python x.py > x.txt
Traceback (most recent call last):
  File "x.py", line 8, in ?
    print 'Test string: ', u'Olá mundo'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: ordinal not in range(128)


-- 
	Ricardo




More information about the Python-list mailing list