gpt4 book ai didi

python - 重定向输出时更改了 Windows 编码

转载 作者:可可西里 更新时间:2023-11-01 13:48:19 26 4
gpt4 key购买 nike

您好,我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com