命令行输出中文乱码的核心原因是终端与程序编码不一致,需从环境、代码、终端三端协同调整:先查终端编码(如windows用chcp),再统一为utf-8,python脚本顶部强制重配sys.stdout编码,ide终端也需单独设置。

命令行输出中文乱码,核心原因是终端编码与程序输出编码不一致,常见于 Windows 的 CMD/PowerShell(默认 GBK)运行 UTF-8 编码的 Python 脚本,或 Linux/macOS 终端 locale 设置异常。解决需从**环境、代码、终端三端协同调整**,不能只改一行 print。
确认并统一编码环境
先查当前终端真实编码:
- Windows CMD:执行 chcp,显示类似 活动代码页: 936(即 GBK)
- PowerShell:运行 [Console]::OutputEncoding,看是否为 UTF-8
- Linux/macOS:运行 locale | grep -i utf,确保 LANG=en_US.UTF-8 或 zh_CN.UTF-8
若不匹配,临时修正(以 Windows CMD 为例):
- 运行 chcp 65001 切换为 UTF-8(重启后失效)
- Python 脚本开头加:import os; os.system('chcp 65001 >nul')(仅 Windows 有效)
Python 代码层强制指定输出编码
避免依赖系统默认,显式控制 stdout 编码:
- Python 3.7+ 推荐方式(安全可靠):
import sys; sys.stdout.reconfigure(encoding='utf-8') - 兼容旧版本(如 Python 3.6):
import io, sys; sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') - 打印前手动编码(不推荐,仅应急):
print('中文'.encode('utf-8').decode('utf-8')) —— 实际无意义,仅示意
IDE 或编辑器终端设置同步
VS Code、PyCharm 内置终端常独立于系统终端,需单独配置:
- VS Code:设置中搜索 terminal.integrated.defaultProfile.windows,设为 PowerShell;再搜 terminal.integrated.env.windows,添加:
"PYTHONIOENCODING": "utf-8" - PyCharm:File → Settings → Tools → Terminal → Shell path,勾选 Activate environment in terminal,并确保项目解释器支持 UTF-8
终极兼容写法(推荐直接复制)
在脚本最顶部加入以下几行,覆盖大多数场景:
import sys import locale <h1>强制 stdout 使用 UTF-8</h1><p>if hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8') else: import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')</p><h1>可选:同步 stderr 和 stdin</h1><p>if hasattr(sys.stderr, 'reconfigure'): sys.stderr.reconfigure(encoding='utf-8') if hasattr(sys.stdin, 'reconfigure'): sys.stdin.reconfigure(encoding='utf-8') </p>
之后所有 print('你好') 都能正确显示,无需额外 encode/decode。











