Yoav Vollansky
Yoav Vollansky

Reputation: 203

Encoding error with sublime text 2 and Python

After struggling with encoding problems in a rows-rich code in sublime text 2, I decided to make a simpler experiment. I used the following code, trying to print in Chinese :

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

print('你好')

When running in sublime text, I receive the following error:

File "D:\xampp\htdocs\stam\chinese print try.py", line 4, in <module>
print('\u4f60\u597d')
File "d:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: character           maps to <undefined>
[Finished in 0.2s with exit code 1]

And here is the big but. When I run the code through the regular Python GUI, everything's fine. It prints.

I tried looking here but didn't understand how it can help me (which could indeed be my lack of understanding in sublime text configuration).

Thanks for your kind help.

Upvotes: 0

Views: 1278

Answers (2)

Bill Zhao
Bill Zhao

Reputation: 31

Similar to this printing UTF-8 in Python 3 using Sublime Text 3

You can modify or add a new build and include "env": {"PYTHONIOENCODING": "utf8"} in the build file.

For example, the new build file should look like the following (windows 7):

{
    "cmd": ["your_path\\python.exe", "-u", "$file"],
    "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)",
    "selector": "source.python",
    "env": {"PYTHONIOENCODING": "utf8"}
}

Upvotes: 1

D_S_toowhite
D_S_toowhite

Reputation: 683

See this: http://blog.sina.com.cn/s/blog_765abd7b0101dtbw.html

I do these two things which finally solved this problem:

  • In code, addimport sys reload(sys) sys.setdefaultencoding("utf-8")
  • in Python.sublime-build, add "encoding":"utf-8"

Upvotes: 0

Related Questions