简体   繁体   中英

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.

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"}
}

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

I do these two things which finally solved this problem:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM