python异常之UnicodeEncodeError 'ascii'

很多时候,你想打印一些数据,想直观的看看结果。可是!你在python中的print()语句报错了。

如下:

1
2
3
4
Traceback (most recent call last):
File "test_aci.py", line 2, in <module>
print('xt\u7ecf')
UnicodeEncodeError: 'ascii' codec can't encode character '\u7ecf' in position 2: ordinal not in range(128)

你查阅各种博客,知道了是编码问题,可是试了几种方法无法解决。可能在前面加# coding=utf-8,这种思路是对的,但是解决的是sys编码.而你遇到的是print编码问题,就好像你手流血了,你包扎脚。..。。就没有什么好点的方法吗?
那我们怎么包扎手呢?
在你的py文件合适的位置加上这么一句:
如果你不知道在哪,在import 后面加就行。。
python2:

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

python3:

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

问题解决,完美!

可以看出,这是stdout问题,不是加个#coding:utf-8就可以的。这主要是环境配置问题,你当然可以修改环境配置,是个一劳永逸的办法,但很多时候,你拿不到root权限呀,哈哈。

每天一点,进步不难。