views:

378

answers:

2

The title explains it well. I have set up Notepad++ to open the Python script in the command prompt when I press F8 but all Swedish characters looks messed up when opening in CMD but perfectly fine in e.g IDLE.

This simple example code:

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
print "åäö"

Looks like this.

As you can see the output of the batch file I use to open Python in cmd below shows the characters correctly but not the Python script above it. How do I fix this? I just want to show the characthers correctly I dont necessarily have too use UTF-8.

I open the file in cmd using this method.

Solved it: Added a "chcp 1252" line at the top of the batch file and then a cls line below it to remove the message about what character encoding it uses. Then I used "# -- coding: cp1252 --" in the python script and changed the font in cmd to Lucida Console. This is done by clicking the cmd icon at the top right of the cmd window and go into properties.

+4  A: 

You're printing out UTF-8 bytes, but your console is not set to UTF-8. Either write Unicode as UTF-16, or set your console codepage to UTF-8.

print u"åäö"
Ignacio Vazquez-Abrams
Simply writing print "åäö" in a cmd window after starting in it python works and also print u"åöä" but not saving a file. The file only contains print u"åäö" and produces an error.
Alex
That's because the Python REPL decodes it using the console's encoding when you enter it into the console.
Ignacio Vazquez-Abrams
A: 

Python will normally convert Unicode strings to the Windows console's encoding. Note that to use Unicode properly, you need Unicode strings (e.g., u'string') and need to declare the encoding the file is saved in with a coding: line.

For example, this (saved in UTF-8 as x.py on my system):

# coding: utf8
print u"åäö"

Produces this:

C:\>chcp
Active code page: 437

C:\>x
åäö

You'll only be able to successfully print characters that are supported by the active code page.

Mark Tolonen