您的位置:首页 > 编程语言 > Python开发

Windows 命令行下解决python utf-8中文输出的终极解决方案!

2012-12-27 11:35 741 查看
代码参考了这里:http://wiki.python.org/moin/PrintFails

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

原理就是:

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

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

# -*- 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下兼容了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: