在 Ubuntu 下使用 Python 时,编码问题通常出现在:读取/写入文件、终端输出、subprocess、网络请求、数据库等场景。下面按「常见原因 + 解决方式」给你一个实用清单。
Python 3 默认源码是 UTF-8,字符串是 str(Unicode)
但外部环境(终端、文件、系统 locale)可能不是 UTF-8,就会炸。
报错示例
UnicodeEncodeError: 'ascii' codec can't encode characters
✅ 解决:
locale
如果不是 UTF-8,执行:
sudo apt install locales
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
❌ 错误写法:
open("a.txt").read()
✅ 正确写法(显式编码):
with open("a.txt", encoding="utf-8") as f:
data = f.read()
写文件:
with open("a.txt", "w", encoding="utf-8") as f:
f.write("中文")
通常是 stdout 编码不是 UTF-8
✅ 临时解决:
export PYTHONIOENCODING=utf-8
✅ 永久(加入 ~/.bashrc):
echo 'export PYTHONIOENCODING=utf-8' >> ~/.bashrc
source ~/.bashrc
subprocess.run(["ls"], capture_output=True)
✅ 指定编码:
subprocess.run(
["ls"],
capture_output=True,
encoding="utf-8"
)
open("a.txt", encoding="gbk")
或用 chardet 自动识别:
pip install chardet
import chardet
raw = open("a.txt", "rb").read()
enc = chardet.detect(raw)["encoding"]
text = raw.decode(enc)
Python 2 默认是 bytes + ascii
✅ 顶部加:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
print(sys.getdefaultencoding())
print(sys.stdout.encoding)
✅ 永远显式指定 encoding="utf-8"
✅ 系统 locale 必须是 UTF-8
✅ 不要在 Python 3 里混用 bytes 和 str
如果你能贴一段具体报错信息或代码,我可以直接帮你定位是哪一类问题。