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)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文鏈接:https://blog.csdn.net/th_num/article/details/80685389
Python3中遇到UnicodeEncodeError: 'ascii' codec can't encode characters in ordinal not in range(128)
但是在windows上面運行代碼正常。原因是因為:linux系統語言導致的。
查看了一下系統環境編碼 >>> import sys >>> sys.stdout.encoding 'US-ASCII'
- 1
- 2
- 3
而另一臺能正常打印的機器是 en_US.UTF-8
解決辦法
(1)設置環境變量LANG
在linux或Mac上設置環境變量的方式一樣,編輯~/.bash_profile文件(’~’指的是用戶登錄后的默認目錄),添加一行:
export LANG="en_US.UTF-8"- 1
保存退出后重新打開命令行控制臺
(2)使用PYTHONIOENCODING
在運行python命令前添加參數 PYTHONIOENCODING=utf-8 python test.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('中文')- 1
- 2
- 3
- 4
總結
以上是生活随笔為你收集整理的Python3中遇到UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in ordinal not in range(128)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 腾讯-视频打标签算法探讨
- 下一篇: 清华CrossWOZ,助你徒手搭建任务导