Printing æøå in Python3 crashes


#1

Hi!

I have a problem with printing Norwegian characters æøå when running script in Atom.
The script

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

print('æøå')

returns

3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
Traceback (most recent call last):
  File "/Users/sivert/Documents/Python/CSV/csv_processing.py", line 13, in <module>
    print('\xe6\xf8\xe5')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
[Finished in 0.05s]

when i hit cmd+i (Run script). However the script runs perfectly when running it from terminal, so there must be something not set up right with Atom.

How do I fix this?


#2

Hello.

Atom is not to blame for this one -
you’ll have to query how the extension packages does its job.

My guess… you are running part of your code.
This code is placed into a temporary file for the execution, by the extension package.
It is the encoding of that temporary file that is the problem (maybe).

Which package are you using for this task?

Cheers.


#3

Forgive me, noobie here.

The package I’m using to run the scripts is this one:


#4

Hello.

I was trying the code…

  • In VSCode also had issues.
  • Calling saved file from a terminal -> also a problem
PS C:\Windows\System32> cd c:\zoo
PS C:\zoo> python norw.py
  File "norw.py", line 2
SyntaxError: Non-ASCII character '\xc3' in file norw.py on line 2, but no encoding declared; 
see http://python.org/dev/peps/pep-0263/ for details

Perhaps there is a way of resolving the issue from inside the editor.
What does http://python.org/dev/peps/pep-0263/ say?

image

This line would probably only be used if running the whole file…
# -*- coding: utf-8 -*-
…and this should be set to…?


#5

Atom is set to UTF-8 down in the right corner.


#6

Perhaps…
http://scratchpad.wikia.com/wiki/Character_Encoding_Recommendation_for_Languages
https://stackoverflow.com/questions/664372/using-norwegian-letters-æøå-in-python

image

Also…
What happens if you type in python --version in the terminal?

UPDATE:


#7

I don’t know why script doesn’t work, since it’s using the correct version of Python.


#8

Fascinating results:

  • Windows 7
  • Atom V1.20.0
  • Python V3.6.1


Works in SCRIPT
Works in SCRIPT

Does not work
Does not work.

Works in TERMINAL
Works in TERMINAL

In that other editor:
image


#10

I had the same problem with printing German characters.
Adding this at the beginning of the file solved the problem:

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding=‘utf-8’)
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding=‘utf-8’)