Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnicodeEncodeError when redirecting stdout [duplicate]

Tags:

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?

like image 731
dbr Avatar asked Feb 08 '10 19:02

dbr


1 Answers

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.

like image 183
Ignacio Vazquez-Abrams Avatar answered Oct 25 '22 02:10

Ignacio Vazquez-Abrams