1

Python correctly handles printing Unicode until you try to pipe it to a file.

Compare:

$ python -c "print u'\u2018'"
‘

To:

$ python -c "print u'\u2018'" > out.txt
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode    character u'\u2018' in position 0: ordinal not in range(128)

Why does this happen?

Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
  • http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python – ErlVolton Oct 17 '14 at 14:56
  • 1
    Set PYTHONIOENCODING or encode explicitly. There is no terminal to autodetect the encoding for when you redirect. – Martijn Pieters Oct 17 '14 at 14:56
  • python -c "import sys; reload(sys);sys.setdefaultencoding('utf-8');print u'\u2018'" > out.txt http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python – Adem Öztaş Oct 17 '14 at 15:02

0 Answers0