python3無法print中文的解決方案

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'

治標不治本的解決方案有兩種:

  1. 在命令行前指定編碼
$ PYTHONIOENCODING=utf-8 python test.py
hello world
你好,世界
  1. 在代碼中指定編碼
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 ,一切正常了

題圖
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容