python 的編碼問題很讓人窩火,本來以為 python3 不會再遇到各種奇怪的編碼問題,沒想到又跳到一個大坑里。在 shell 環(huán)境中,用 python3 print 中文報編碼錯誤
代碼如下:
$ cat test.py
print('hello world')
print('你好,世界')
報錯內(nèi)容:
$ python test.py
hello world
Traceback (most recent call last):
File "test.py", line 2, in <module>
print('\u4f60\u597d\uff0c\u4e16\u754c')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
原來是標準輸出的編碼問題,用 ipython 查看:
In [1]: import sys
In [2]: sys.stdout.encoding
Out[2]: 'ANSI_X3.4-1968'
治標不治本的解決方案有兩種:
- 在命令行前指定編碼
$ 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('你好,世界')
這兩種方式都讓人覺得惡心,加這些累贅代碼讓人心煩意亂,以下才是終極解決方案:指定系統(tǒng)的編碼,將以下內(nèi)容加入到你的 shell 配置文件中
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
重啟 shell ,一切正常了

題圖