当前位置:首页 > Python > 正文

Python中文输出问题解决方案 - 解决Python输出不了中文乱码

Python输出不了中文?5种有效解决方案

问题原因分析

Python无法输出中文通常由以下原因导致:

  • 文件编码未设置为UTF-8
  • 终端/IDE编码不匹配
  • Windows系统默认GBK编码
  • 环境变量配置缺失
  • Python版本差异处理

解决方案

1. 添加文件编码声明

在Python文件开头添加编码声明:

# -*- coding: utf-8 -*-
print("你好,世界!")  # 正常输出中文

2. 修改环境编码(Windows系统)

临时解决方案(命令提示符):

chcp 65001  # 切换到UTF-8编码
python your_script.py

3. 永久修改环境变量

添加系统环境变量:

变量名:PYTHONIOENCODING
变量值:UTF-8

4. 代码中强制设置编码

import sys
import codecs

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
print("中文内容")

5. IDE/编辑器设置(以VSCode为例)

修改settings.json:

"files.encoding": "utf8",
"terminal.integrated.defaultProfile.windows": "Command Prompt",
"terminal.integrated.shellArgs.windows": ["/K", "chcp 65001"]

各操作系统配置要点

系统 解决方案
Windows chcp 65001 + 环境变量设置
macOS/Linux export LANG=en_US.UTF-8
所有系统 文件添加# -*- coding: utf-8 -*-

Python 2.x特殊处理

# Python 2需要额外处理
reload(sys)
sys.setdefaultencoding('utf8')
print u"中文内容"

终极解决方案

推荐组合方案:

  1. 文件开头添加编码声明
  2. 设置系统环境变量PYTHONIOENCODING=UTF-8
  3. IDE中配置UTF-8支持
  4. 代码中使用unicode字符串(Python2)

常见错误排查

  • 错误:SyntaxError: Non-UTF-8 code

    → 文件未保存为UTF-8格式

  • 错误:UnicodeEncodeError: 'gbk' codec can't encode

    → 终端编码不匹配

发表评论