在测试环境运行正常,但换一台机器运行时报UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-3: ordinal not in range(128)错误
原因:
python3默认就使用utf8编码,而当前环境的运行命令的编码不是utf-8
解决办法:
-
设置环境变量LANG
编辑~/.bash_profile文件,添加一行:
export LANG=“en_US.UTF-8”
生效文件
source ~/.bashrc -
使用PYTHONIOENCODING,只针对python设定相应编码
设置同上,添加下面的语句
PYTHONIOENCODING=utf-8
export PYTHONIOENCODING -
重新定义标准输出
在代码中添加 下面代码
import sys
import codecs
sys.stdout = codecs.getwriter(“utf-8”)(sys.stdout.detach())