在 Ubuntu 下设置 Python 编码,常见有系统/文件编码、Python 内部默认编码、源码文件编码几种情况,下面按场景说明:
locale
重点关注:
LANGLC_ALLLC_CTYPE推荐设置为 UTF-8:
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
(永久生效可写入 ~/.bashrc 或 /etc/environment)
在 .py 文件第一行或第二行声明:
# -*- coding: utf-8 -*-
或
# coding: utf-8
Python 3 默认就是 UTF-8,一般不用写,但写了更安全。
Python 3 默认使用 UTF-8,不要改 sys.setdefaultencoding(那是 Python 2 的黑科技,Python 3 已移除)。
查看:
import sys
print(sys.getdefaultencoding())
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
有时终端乱码,可设置:
import sys
sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')
(Python 3.7+)
不要依赖默认编码,读写文件一定要写:
with open('a.txt', 'r', encoding='utf-8') as f:
data = f.read()
with open('b.txt', 'w', encoding='utf-8') as f:
f.write('中文')
如果你遇到的是具体报错(如 UnicodeDecodeError),可以把报错贴出来,我帮你精确定位。