22

I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout elsewhere (or capture it with the subprocess module), I get a UnicodeEncodeError:

$ cat example.py 
print u'Example: \u00F1'
$ python example.py 
Example: ñ
$ python example.py > /dev/null
Traceback (most recent call last):
  File "example.py", line 1, in <module>
    print u'Example: \u00F1'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)

Why is this? How can I fix it?

dbr
  • 165,801
  • 69
  • 278
  • 343
  • 1
    http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python is essentially the same question, the answers solved the problem I was having (hopefully).. – dbr Feb 09 '10 at 01:17

1 Answers1

9

Pipes that don't lead to the terminal don't have an encoding, therefore you'll need to check sys.stdout.isatty() and encode if needed.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358