4

How do you set the default encoding Python uses with sys.stdout when run from a terminal program like Gnome-Terminal?

If I execute a Python script inside Gnome-Terminal, I get the notorious "UnicodeEncodeError: 'ascii' codec can't encode character" error if the script tries to print unicode characters. However, even though Gnome-Terminal's encoding is set to "UTF-8", if I print sys.stdout.encoding it shows "ANSI_X3.4-1968".

Minimal code to reproduce the error is:

python -c 'import sys; print sys.stdout.encoding; print u"\u0411\n"' 

Why isn't Python using the terminal's encoding of utf-8?

Note, I'm not asking how to convert my string to ASCII.

7
  • 2
    what does echo $LANG and echo $LC_ALL print? Commented Feb 28, 2017 at 18:40
  • 2
    Tried # -*- coding: utf-8 -*- at the top of your script file ? Commented Feb 28, 2017 at 18:43
  • @Szabolcs There's no script, as far as I understood -- just one command. Commented Feb 28, 2017 at 18:48
  • Can you show output of locale command in your terminal, please? Commented Feb 28, 2017 at 18:48
  • 1
    @Szabolcs and the upvoters. # coding: utf8 declares the encoding of the source file and nothing else. Commented Mar 1, 2017 at 5:03

1 Answer 1

4

Try setting the PYTHONIOENCODING variable, or using the solutions in this question.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.