解决 UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-20: ordinal not in range

python中因编码问题报错:

Traceback (most recent call last):
  File "a*.py", line 61, in <module>
    m*w.a*b()
  File "a*e.py", line 50, in a
    print (ab)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-20: ordinal not in range(128)

解决方案:
在python2中

# encoding=utf8  
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')   

python3中使用上述代码会报错,NameError: name 'reload' is not defined,可以导入importlib替代。

import importlib
importlib.reload(sys)

1.在python运行命令参数前添加PYTHONIOENCODING=utf-8:

PYTHONIOENCODING=utf-8  python pythonfilename.py

2.重新定义标准输出

import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

3.设置环境变量
Mac和Linux设置环境变量方式相同,打开~/.bash_profile(.zshrc)文件,添加

export LANG="en_US.UTF-8"

Reference:
https://blog.csdn.net/th_num/article/details/80685389

你可能感兴趣的:(问题解决)