设为首页 加入收藏

TOP

Python print报ascii编码异常的靠谱解决办法
2017-10-09 16:54:31 】 浏览:5706
Tags:Python print ascii 编码 异常 解决 办法

之前遇到此异常UnicodeEncodeError: 'ascii' codec can't encode characters...,都是用这种方式解决:sys.setdefaultencoding('utf-8')

今天看到如下文章,阐述了此方式的弊端:

http://blog.ernest.me/post/python-setdefaultencoding-unicode-bytes

但此文章只考虑了未使用第三方库的情况下的解决办法,而第三方库里如果也有print的话,就束手无策了,总不能把第三方的所有print都加上encode吧。

另外此文中说的修改编码为utf8的隐患,其实都是因为没有使用unicode字符串或两种字符串混用而已,如果项目中规定只可使用u'unicode字符串',上述隐患即可基本避免。归根结底最大的风险就是第三方库的不可控,print编码和unicode字符串都不可控,所以不能使用setdefaultencoding。

 

我这次是在用Java启动python时,print中文,就会报ascii的异常,我发现此种情况下sys.stdout.encoding其实为None,而Ubuntu中普通命令行时此变量则是UTF-8。

那如何修改sys.stdout.encoding呢?(直接修改会报错TypeError: readonly attribute)

所以最终找到http://www.macfreek.nl/memory/Encoding_of_Python_stdout

python2修改方式(python3略不同,原文中也有写)

1 if sys.stdout.encoding != 'UTF-8':
2     sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'strict')
3 if sys.stderr.encoding != 'UTF-8':
4     sys.stderr = codecs.getwriter('utf-8')(sys.stderr, 'strict')

这样就完美解决输出中文时的ascii编码异常了,而且也不用重新设置sys的默认编码。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python-docx 使用教程 下一篇Anaconda安装第三方包(whl文件)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目