温馨提示×

ubuntu python编码怎么设

小樊
45
2026-10-04 11:16:43
栏目: 编程语言

在 Ubuntu 下设置 Python 编码,常见有系统/文件编码、Python 内部默认编码、源码文件编码几种情况,下面按场景说明:


一、查看当前编码环境

locale

重点关注:

  • LANG
  • LC_ALL
  • LC_CTYPE

推荐设置为 UTF-8:

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

(永久生效可写入 ~/.bashrc 或 /etc/environment)


二、Python 源码文件编码(最常用)

在 .py 文件第一行或第二行声明:

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

或

# coding: utf-8

Python 3 默认就是 UTF-8,一般不用写,但写了更安全。


三、Python 运行时的默认编码

Python 3(推荐)

Python 3 默认使用 UTF-8,不要改 sys.setdefaultencoding(那是 Python 2 的黑科技,Python 3 已移除)。

查看:

import sys
print(sys.getdefaultencoding())

Python 2(不推荐但说明)

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

四、标准输入输出编码

有时终端乱码,可设置:

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

(Python 3.7+)


五、文件读写时指定编码(最重要)

不要依赖默认编码,读写文件一定要写:

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

with open('b.txt', 'w', encoding='utf-8') as f:
    f.write('中文')

六、Ubuntu 终端中文乱码排查

  1. 确认 locale 是 UTF-8
  2. 终端软件编码设为 UTF-8
  3. Python 文件用 UTF-8 保存

七、推荐做法总结 ✅

  • 用 Python 3
  • 全程 UTF-8
  • 文件操作 显式指定 encoding
  • 不修改 Python 默认编码

如果你遇到的是具体报错(如 UnicodeDecodeError),可以把报错贴出来,我帮你精确定位。

0 踩