解決方案有兩種:
- 在命令行前指定編碼
$ PYTHONIOENCODING=utf-8 python test.py
hello world
你好,世界
- 在代碼中指定編碼
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
print('hello world')
print('你好,世界')
3.終極解決方案是:指定系統的編碼,將以下內容加入到系統配置文件中:
sudo apt-get install locales
查看系統支持的字符集:locale -a
拉取中文編碼:locale-gen zh_CN.UTF-8
再次查看:locale-a, 發現多了ZH開頭的字符集
修改文件/etc/default/locale
LANG = zh_CN.UTF-8(這個根據實際查詢出來的名稱修改)
重啟機器(不一定需要)
export LANG=zh_CN.UTF-8
python zh pth problem:
str = str.encode('utf-8')
