如果用sublime在控制台输出中文乱码
第一步:在代码的加入
#-*- coding : utf-8 -*-
这个声明主要针对文件里面的中文,python源码中文依然报错;
加入上面代码后执行。失败后继续往下
第二步:在中文前面加u。例如u'我是中文'
执行时如果是UnicodeEncodeError: 'ascii' codec can't encode characters in position 继续往下进行
第三步:加入以下代码
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
#以上两行代码是设置默认的编码字符
执行时如果报[Decode error - output not utf-8]则继续往下看
第四步:打开sublime的preferences--browse packages找到Default文件夹中的exec.py程序,进行如下修改即可
打开exec.py.找到类ExecCommand的append_data函数,在以下位置添加代码
作用为当输入读取为utf-8失败时,尝试使用gbk编码。
- def append_data(self, proc, data):
- if proc != self.proc:
- # a second call to exec has been made before the first one
- # finished, ignore it instead of intermingling the output.
- if proc:
- proc.kill()
- return
- #add start
- #起始位置
- is_decode_ok = True;
- try:
- str = data.decode(self.encoding)
- except:
- is_decode_ok = False
- if is_decode_ok==False:
- try:
- str = data.decode("gbk")
- except:
- str = "[Decode error - output not " + self.encoding + " and gbk]\n"
- proc = None
- #起始位置
- #add end
- # Normalize newlines, Sublime Text always uses a single \n separator
- # in memory.
- str = str.replace('\r\n', '\n').replace('\r', '\n')
- self.output_view.run_command('append', {'characters': str, 'force': True, 'scroll_to_end': True})
参考资料:
- https://app.yinxiang.com/shard/s3/nl/16051428/f3e946ae-8972-42e7-becd-e08c38d5e01a/
- http://blog.csdn.net/bbdxf/article/details/25594703