出錯信息:
[UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128]
解決方案:
(1)設置環境變量LANG
在linux或Mac上設置環境變量的方式一樣,編輯~/.bash_profile文件(’~’指的是用戶登錄後的默認目錄),添加一行:
export LANG="en_US.UTF-8"
添加完記得source .bash_profile一下使之生效。
(2)使用PYTHONIOENCODING
在運行python命令前添加參數 PYTHONIOENCODING=utf-8 python test.py
該參數的解釋可查看官方文檔:
https://docs.python.org/3.6/using/cmdline.html#envvar-PYTHONIOENCODING
(3)重新定義標準輸出
在代碼中添加 sys.stdout = codecs.getwriter(“utf-8”)(sys.stdout.detach()) ,使代碼變爲
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
print('中文')