您好,我有以下 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?
谢谢
最佳答案
您正在使用 Windows。这是因为 Windows 7 控制台不理解 UTF-8。因此,当您显示标准输出时,它需要编码为 Windows 可以显示的内容。
Luciano Ramalho 的书 Fluent Python很好地解释了这一点。
关于python - 重定向输出时更改了 Windows 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724398/