温馨提示×

centos python编码怎么设

小樊
50
2026-09-18 11:18:36
栏目: 编程语言

在 CentOS 上设置 Python 编码,常见有系统环境编码、Python 解释器默认编码、代码里指定编码几种方式,下面按场景说明。


一、查看当前编码

locale

或 Python 里:

import sys
print(sys.getdefaultencoding())
print(sys.stdout.encoding)

二、设置系统 / 终端编码(推荐 UTF-8)

1. 临时设置(当前会话)

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

2. 永久设置(CentOS 7)

localectl set-locale LANG=en_US.UTF-8

或编辑:

vi /etc/locale.conf

内容:

LANG=en_US.UTF-8

重启或重新登录生效。


三、Python 代码里设置编码

1. Python 2(已淘汰,但老系统常见)

文件开头加:

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

设置默认输出编码:

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

2. Python 3(默认就是 UTF-8)

一般不需要设置,若涉及文件:

open('a.txt', 'w', encoding='utf-8')

四、pip / 脚本乱码处理

确保终端是 UTF-8:

echo $LANG

不是 UTF-8 就按上面第二步改。


五、常见问题

  • 中文乱码:90% 是 LANG 不是 UTF-8
  • 写入文件乱码:open 没指定 encoding
  • cron 任务乱码:cron 环境没有 locale,脚本里加:
export LANG=en_US.UTF-8

如果你能说明是 Python2 还是 3、CentOS 几、具体乱码场景,我可以给你更精确的做法。

0 踩