代码参考了这里:http://wiki.python.org/moin/P…

上文对各种系统无法输出奇葩编码的字符做了总结,本文中只针对windows cmd下GBK编码(cp936)但想执行utf-8编码的Python文件进行修改。

原理就是:

Another is to put an intercept between sys.stdout, and the text wrapper.

更多还是看参考文章吧,这里直接贴代码:

[python] view plain copy

– coding: utf-8 –

import sys

class UnicodeStreamFilter:

def __init__(self, target):  
    self.target = target  
    self.encoding = \'utf-8\'  
    self.errors = \'replace\'  
    self.encode_to = self.target.encoding  
def write(self, s):  
    if type(s) == str:  
        s = s.decode(\"utf-8\")  
    s = s.encode(self.encode_to, self.errors).decode(self.encode_to)  
    self.target.write(s)  
      

if sys.stdout.encoding == \’cp936\’:

sys.stdout = UnicodeStreamFilter(sys.stdout)  

if name == \”__main__\”:

a = \"你好\"  
b = u\"你好\"  
print a  
print b  

保存成一个py文件,直接import即可。

这样就实现了linux下和windows下兼容了~

当然如果不知道原来是什么编码,但想转成utf-8编码的话,将上面的if条件删掉即可。