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

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

现象

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

print('中文')

控制台报错:linux

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里执行也能够正常显示。只有在命令行控制台会报错。bash

个人环境是MacOS 10.13.3 中文,Anaconda3 5.0.1函数

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 code

解决办法

(1)设置环境变量LANG

在linux或Mac上设置环境变量的方式同样,编辑~/.bash_profile文件('~'指的是用户登陆后的默认目录),添加一行:orm

export LANG="en_US.UTF-8"

保存退出后从新打开命令行控制台

(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('中文')
相关文章
相关标签/搜索