脚本宝典收集整理的这篇文章主要介绍了Windows 命令行下解决python utf-8中文输出的终极解决方案,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
代码参考了这里: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.
更多还是看参考文章吧,这里直接贴代码:
-- 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下兼容了~
以上是脚本宝典为你收集整理的Windows 命令行下解决python utf-8中文输出的终极解决方案全部内容,希望文章能够帮你解决Windows 命令行下解决python utf-8中文输出的终极解决方案所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。