Windows 下 Python 脚本中文输出乱码问题修复
·
问题现象
在 Windows 系统上运行 Python 脚本时,使用 print() 输出到 stderr 的中文显示为乱码:
�������� 2026 ��Ľڼ���֪ͨ...
�ҵ�֪ͨ: https://www.gov.cn/...
原因分析
Windows 控制台默认使用系统编码(GBK/CP936),而 Python 的 sys.stdout 和 sys.stderr 默认继承控制台编码。当脚本输出 UTF-8 编码的中文字符时,编码不匹配导致乱码。
解决方案
在脚本开头强制将 stdout 和 stderr 设置为 UTF-8 编码:
import io
import sys
# 修复 Windows 控制台编码问题:强制使用 UTF-8
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
关键点
- 位置:必须放在脚本开头,在任意
print语句之前 - 平台检测:使用
sys.platform == 'win32'仅对 Windows 生效,不影响其他系统 - errors 参数:设置为
'replace'可避免因无法编码的字符导致程序崩溃
验证结果
修复后输出正常:
正在搜索 2026 年的节假日通知...
找到通知: https://www.gov.cn/...
正在获取通知内容...
国务院办公厅关于2026年...
(END)
更多推荐


所有评论(0)