首页 > 解决方案 > 重定向输出时更改了 Windows 编码

问题描述

嗨,我有以下 python 文件'test.py':

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

当我跑步时

py test.py

我得到:

utf-8
utf-8

但是当我跑步时

py test.py > test.txt

或者

py test.py | Out-File -FilePath test.txt -Encoding ASCII

我从 test.txt 得到:

cp1252
utf-8

更新:当我运行以下 python 代码时:

import sys, locale
print(sys.getdefaultencoding())
print(locale.getpreferredencoding())

我得到:

utf-8
cp1252

问题:
我可以知道为什么会发生这种情况,我应该怎么做才能在重定向时默认编码为 utf-8?
谢谢

标签: pythonwindows

解决方案


您正在使用 Windows。发生这种情况是因为 Windows 7 控制台不理解 UTF-8。因此,当您显示标准输出时,它需要编码为 Windows 可以显示的内容。

Luciano Ramalho 的书Fluent Python很好地解释了这一点。


推荐阅读