python无法打印中文_python3无法print中文的解决方案
python 的编码问题很让人窝火,本来以为 python3 不会再遇到各种奇怪的编码问题,没想到又跳到一个大坑里。在 shell 环境中,用 python3 print 中文报编码错误
代码如下:$ cat test.py
print('hello world')
print('你好,世界')
报错内容:$ python test.py
hello world
Traceback (most recent call last):
File "test.py", line 2, in
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'
治标不治本的解决方案有两种:在命令行前指定编码$ PYTHONIOENCODING=utf-8 python test.py
hello world
你好,世界在代码中指定编码import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
print('hello world')
print('你好,世界')
这两种方式都让人觉得恶心,加这些累赘代码让人心烦意乱,以下才是终极解决方案:指定系统的编码,将以下内容加入到你的 shell 配置文件中export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
重启 shell ,一切正常了
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
