0

When I copied my program from one RPI to another I suddenly got a lot of errors in the log file. I have narrowed the problem down to a thing related to danish letters ÆØÅ.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-    
print("ABC æøå ÆØÅ")  #Danish characters

On One of my RasberryPies it gives this error.

Traceback (most recent call last):File "test.py", line 5, in <module>
print("ABC \xe6\xf8\xe5 \xc6\xd8\xc5")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-6: ordinal not in range(128)

On the two others i runs perfectly.

Python version Python 3.5.3 Checked danish localization with raspi-config.

-*- coding is the correct way

  • 1
    Hi please provide the code snippet that causes the error. You also might want to consult the guidelines on [how to ask a good question](https://stackoverflow.com/help/how-to-ask) – tituszban Jul 08 '19 at 14:38
  • I have found a difference between the two systems. sys.getfilesystemcoding() return 'ANSI_X3.4-1968' on the RPI that fails. sys.getfilesystemcoding() return 'utf-8' on the RPI that works. Wondering why there is a difference, how I change it, and if it will take care of the error. – Allan Vestergaard Jul 08 '19 at 15:05
  • Possible duplicate of [Correct way to define Python source code encoding](https://stackoverflow.com/questions/728891/correct-way-to-define-python-source-code-encoding) – tituszban Jul 08 '19 at 15:07

1 Answers1

1

Before execute python command, add below lines to your terminal.

export PYTHONIOENCODING=utf-8

Now run python test.py in the same terminal.

Or you can add below lines in top of your test.py file

import sys
sys.setdefaultencoding('utf-8')

For more details, please check following question,

Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58