问题描述
linux 无法输入和显示中文
运行python3打印中文时,报错UnicodeEncodeError,如下
UnicodeEncodeError: 'ascii' codec can't encode characters in position 48-49: ordinal not in range(128)
问题定位
1.在linux终端,打印中文
echo 中文
2.在python解释器,打印中文
print(‘中文’)
解决方法:
1、方法一
安装中文字符集
sudo apt-get -y install language-pack-zh-hans
编辑字符集文件
vim /etc/default/locale
LANG=“zh_CN.UTF-8”
LANGUAGE=“zh_CN:zh:en_US:en”
编辑后立即生效
source /etc/default/locale
2、方法二
vim /etc/locale.conf
LANG=“zh_CN.UTF-8”
LC_ALL=“zh_CN.UTF-8”
LC_CTYPE=“zh_CN.UTF-8”
在python解释器里临时解决
import sys
import io
def setup_io():
sys.stdout = sys.__stdout__ = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', line_buffering=True)
sys.stderr = sys.__stderr__ = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8', line_buffering=True)
setup_io()