1,出現的問題及分析
在Sublime Text3中用ctrl+B運行python程序時,如果要打印輸出英文時正常運行,而輸出中文時則會報錯,具體情況如下:
Traceback (most recent call last): File "D:\PythonWorkplace\test_print_unicode.py", line 3, in <module> print u'程序' UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
分析:參考 https://www.v2ex.com/t/163786
2,解決辦法
(1)修改Sublime Text3中的設置
打開Preference-->Browse Packages...,查看是否存在python文件夾,若沒有,可從Sublime Text2中相似路徑(.../Sublime Text2/Packages)中拷貝Python文件夾,再從Python文件夾下修改Python.sublime-build文件,修改內容如下:
原文件:
{ "cmd": ["python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" }
修改后:
{ "cmd": ["python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "env": {"PYTHONIOENCODING": "utf8"} }
之后即可正常運行python程序而不報錯。
(2) 修改文件頭部
在文件頭部添加如下代碼:
import sys reload(sys) sys.setdefaultencoding('utf-8')
該方法在輸出中文時需要在每個文件頭部都添加,較為麻煩,不太推薦
