Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)

現象

打印任何一種包含有中文的對象,字典、列表、DataFrame、或字符串。好比:html

print('中文')

控制檯報錯:python

Traceback (most recent call last):
  File "printcn.py", line 1, in <module>
    print('\u4e2d\u6587')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

換另一臺機器能夠正常顯示 中文 。或者在PyCharm裏執行也能夠正常顯示。只有在命令行控制檯會報錯。linux

個人環境是MacOS 10.13.3 中文,Anaconda3 5.0.1bash

Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct  6 2017, 12:04:38) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

查找緣由

若是是python 2.X的話須要在文件中加上 # -*- coding: utf-8 -*- 、以及 reload(sys) sys.setdefaultencoding("utf8") 。可是Python3應當默認就使用utf8編碼,並且即便設置了這些也仍然不能正常打印。函數

有些人說用encode('utf-8')函數解決,但若是直接打印字典或DataFrame,總不能每一個元素都encode通常吧。編碼

最終查看了一下系統環境編碼spa

>>> import sys
>>> sys.stdout.encoding
'US-ASCII'

而另外一臺能正常打印的機器是 en_US.UTF-8 命令行

解決辦法

(1)設置環境變量LANG

在linux或Mac上設置環境變量的方式同樣,編輯~/.bash_profile文件('~'指的是用戶登陸後的默認目錄),添加一行:code

export LANG="en_US.UTF-8"

保存退出後從新打開命令行控制檯orm

(2)使用PYTHONIOENCODING

在運行python命令前添加參數 PYTHONIOENCODING=utf-8 python printcn.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('中文')
相關文章
相關標籤/搜索