在 Debian 下设置 Python 编码,常见有系统/终端层面和Python 程序层面两种方式。下面按场景说明。
locale
重点关注:
LANGLC_CTYPEPython 中查看:
import sys
print(sys.getdefaultencoding()) # 默认文件编码(通常为 utf-8)
print(sys.stdout.encoding) # 终端输出编码
sudo dpkg-reconfigure locales
勾选:
en_US.UTF-8
# 或
zh_CN.UTF-8
或者手动:
sudo locale-gen en_US.UTF-8
sudo update-locale LANG=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
可写入:
~/.bashrc
~/.profile
Python 3 默认源码和字符串都是 UTF-8。
源码文件可声明(可选):
# -*- coding: utf-8 -*-
with open("a.txt", "r", encoding="utf-8") as f:
data = f.read()
若终端不是 UTF-8:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
export PYTHONIOENCODING=utf-8
C locale → 中文乱码如果你能说明:
我可以给你更精确的设置方案。