python+sublime text3中文乱码[Decode error

来源:互联网 发布:死亡预告 知乎 编辑:程序博客网 时间:2024/05/22 05:30

如果用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编码。


  1. def append_data(self, proc, data):  
  2.      if proc != self.proc:  
  3.          # a second call to exec has been made before the first one  
  4.          # finished, ignore it instead of intermingling the output.  
  5.          if proc:  
  6.              proc.kill()  
  7.          return  
  8.   
  9.      #add start
  10.      #起始位置
  11.      is_decode_ok = True;  
  12.      try:  
  13.          str = data.decode(self.encoding)  
  14.      except:  
  15.          is_decode_ok = False  
  16.      if is_decode_ok==False:  
  17.          try:  
  18.              str = data.decode("gbk")  
  19.          except:  
  20.              str = "[Decode error - output not " + self.encoding + " and gbk]\n"  
  21.              proc = None 
  22.      #起始位置
  23.      #add end
  24.      # Normalize newlines, Sublime Text always uses a single \n separator  
  25.      # in memory.  
  26.      str = str.replace('\r\n''\n').replace('\r''\n')  
  27.   
  28.      self.output_view.run_command('append', {'characters': str, 'force'True'scroll_to_end'True})  


参考资料:

  1. https://app.yinxiang.com/shard/s3/nl/16051428/f3e946ae-8972-42e7-becd-e08c38d5e01a/
  2. http://blog.csdn.net/bbdxf/article/details/25594703

原创粉丝点击