解決 UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-20: ordinal not in range
阿新 • • 發佈:2018-12-17
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"