温馨提示×

debian python编码怎么设置

小樊
39
2026-10-08 01:35:21
栏目: 编程语言

在 Debian 上设置 Python 编码,常见场景和做法如下:


一、查看当前默认编码

python3 -c "import sys; print(sys.getdefaultencoding())"
python3 -c "import locale; print(locale.getpreferredencoding())"

二、通过环境变量设置(推荐)

1. 设置 UTF-8(最常用)

编辑 ~/.bashrc 或 /etc/profile:

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

生效:

source ~/.bashrc

2. 设置 Python 强制 UTF-8(Python 3.7+)

export PYTHONUTF8=1

或在运行脚本时:

PYTHONUTF8=1 python3 script.py

三、Debian 系统语言支持(关键)

如果系统没装 UTF-8 locale:

sudo dpkg-reconfigure locales

勾选:

en_US.UTF-8

生成后重启或重新登录。

查看:

locale

四、Python 代码层面设置

1. 源文件声明(Python 2 常用,Python 3 默认 UTF-8)

# -*- coding: utf-8 -*-

2. 读取/写入文件时指定编码

with open("file.txt", "r", encoding="utf-8") as f:
    data = f.read()

3. 标准输出编码

import sys
sys.stdout.reconfigure(encoding="utf-8")

五、Python 2 特别说明(不推荐再用)

export PYTHONIOENCODING=utf-8

或修改 sitecustomize.py:

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

六、推荐最佳实践

✅ Debian + Python 3
✅ 系统 locale 设为 *.UTF-8
✅ 文件操作显式指定 encoding="utf-8"
❌ 不要依赖默认编码


如果你有具体报错信息(如 UnicodeEncodeError),可以贴出来,我帮你精准定位。

0 踩