python能print中文吗_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 ,一切正常了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值