Python3—UnicodeEncodeError 'ascii' codec can't encode characters in position 0-1

问题描述
使用python3的时候,报错信息
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range(128)

网上解释

网上给出的解释:错误的使用decode和encode方法会出现这种异常。例如使用decode方法将Unicode字符串转化的时候:

s = u'中文'
s.decode('utf-8')
print s

但是将这个例子放到python3环境中,会报错
AttributeError: ‘str’ object has no attribute ‘decode’
熟悉python历史的朋友会知道,为了解决编码问题,在python3中,所有的字符串都是使用Unicode编码,统一使用str类型来保存,而str类型没有decode方法,所以网上给出的方向并不适合我的问题。

输出

既然字符编码、代码都没有错,那么问题肯定出在print上面。这时我开始关注错误信息中的ascii。因为在一般python3环境中,输出时会将Unicode转化为utf-8。为了解开这个疑惑,查看了输出编码

>>>import sys
>>>sys.stdout.encoding
'ANSI_X3.4-1968'

竟然是ANSI_X3.4-1968,所以任何中文都会报错。哈哈,终于定位问题啦。

解决方案

定位问题后,解决办法就很简单啦

使用PYTHONIOENCODING
运行python的时候加上PYTHONIOENCODING=utf-8,即

PYTHONIOENCODING=utf-8 python your_script.py

猜你喜欢

转载自blog.csdn.net/th_num/article/details/80450607