在 CentOS 上设置 Python 编码,常见有系统环境编码、Python 解释器默认编码、代码里指定编码几种方式,下面按场景说明。
locale
或 Python 里:
import sys
print(sys.getdefaultencoding())
print(sys.stdout.encoding)
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
localectl set-locale LANG=en_US.UTF-8
或编辑:
vi /etc/locale.conf
内容:
LANG=en_US.UTF-8
重启或重新登录生效。
文件开头加:
# -*- coding: utf-8 -*-
设置默认输出编码:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
一般不需要设置,若涉及文件:
open('a.txt', 'w', encoding='utf-8')
确保终端是 UTF-8:
echo $LANG
不是 UTF-8 就按上面第二步改。
LANG 不是 UTF-8open 没指定 encodingexport LANG=en_US.UTF-8
如果你能说明是 Python2 还是 3、CentOS 几、具体乱码场景,我可以给你更精确的做法。