在 Debian 上设置 Python 编码,常见场景和做法如下:
python3 -c "import sys; print(sys.getdefaultencoding())"
python3 -c "import locale; print(locale.getpreferredencoding())"
编辑 ~/.bashrc 或 /etc/profile:
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
生效:
source ~/.bashrc
export PYTHONUTF8=1
或在运行脚本时:
PYTHONUTF8=1 python3 script.py
如果系统没装 UTF-8 locale:
sudo dpkg-reconfigure locales
勾选:
en_US.UTF-8
生成后重启或重新登录。
查看:
locale
# -*- coding: utf-8 -*-
with open("file.txt", "r", encoding="utf-8") as f:
data = f.read()
import sys
sys.stdout.reconfigure(encoding="utf-8")
export PYTHONIOENCODING=utf-8
或修改 sitecustomize.py:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
✅ Debian + Python 3
✅ 系统 locale 设为 *.UTF-8
✅ 文件操作显式指定 encoding="utf-8"
❌ 不要依赖默认编码
如果你有具体报错信息(如 UnicodeEncodeError),可以贴出来,我帮你精准定位。