代码参考了这里:http://wiki.python.org/moin/P...python
上文对各类系统没法输出奇葩编码的字符作了总结,本文中只针对windows cmd下GBK编码(cp936)但想执行utf-8编码的Python文件进行修改。linux
原理就是:windows
Another is to put an intercept between sys.stdout, and the text wrapper.app
更多仍是看参考文章吧,这里直接贴代码:编码
[python] view plain copycode
import sys utf-8
class UnicodeStreamFilter:get
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':cmd
sys.stdout = UnicodeStreamFilter(sys.stdout)
if name == "__main__":it
a = "你好" b = u"你好" print a print b
保存成一个py文件,直接import便可。
这样就实现了linux下和windows下兼容了~
固然若是不知道原来是什么编码,但想转成utf-8编码的话,将上面的if条件删掉便可。