Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)...
現(xiàn)象
打印任何一種包含有中文的對(duì)象,字典、列表、DataFrame、或字符串。比如:
print('中文')控制臺(tái)報(bào)錯(cuò):
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)換另外一臺(tái)機(jī)器可以正常顯示?中文?。或者在PyCharm里執(zhí)行也可以正常顯示。只有在命令行控制臺(tái)會(huì)報(bào)錯(cuò)。
我的環(huán)境是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應(yīng)當(dāng)默認(rèn)就使用utf8編碼,而且即使設(shè)置了這些也仍然不能正常打印。
有些人說(shuō)用encode('utf-8')函數(shù)解決,但如果直接打印字典或DataFrame,總不能每個(gè)元素都encode一般吧。
最終查看了一下系統(tǒng)環(huán)境編碼
>>> import sys >>> sys.stdout.encoding 'US-ASCII'而另一臺(tái)能正常打印的機(jī)器是?en_US.UTF-8?
解決辦法
(1)設(shè)置環(huán)境變量LANG
在linux或Mac上設(shè)置環(huán)境變量的方式一樣,編輯~/.bash_profile文件('~'指的是用戶登錄后的默認(rèn)目錄),添加一行:
export LANG="en_US.UTF-8"保存退出后重新打開(kāi)命令行控制臺(tái)
(2)使用PYTHONIOENCODING
在運(yùn)行python命令前添加參數(shù)?PYTHONIOENCODING=utf-8 python printcn.py?
該參數(shù)的解釋可查看官方文檔:https://docs.python.org/3.6/using/cmdline.html#envvar-PYTHONIOENCODING
(3)重新定義標(biāo)準(zhǔn)輸出
在代碼中添加?sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())?,使代碼變?yōu)?#xff1a;
import sys import codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) print('中文')?
轉(zhuǎn)載于:https://www.cnblogs.com/qhlblog/p/8622109.html
總結(jié)
以上是生活随笔為你收集整理的Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: React- jsx的使用可以渲染htm
- 下一篇: OSI七层协议模型