你好,我有以下 python 文件“test.py”:
import sys
print(sys.stdout.encoding)
sys.stdout.reconfigure(encoding='utf-8')
print(sys.stdout.encoding)
当我跑步时
py test.py
I get:
utf-8
utf-8
但当我跑步时
py test.py > test.txt
or
py test.py | Out-File -FilePath test.txt -Encoding ASCII
我从 test.txt 得到:
cp1252
utf-8
当我跑步时:
import sys, locale
print(sys.getdefaultencoding())
print(locale.getpreferredencoding())
I get:
utf-8
cp1252
问题:
我可以知道为什么会发生这种情况吗?我应该做什么才能使重定向时默认编码为 utf-8?
Thanks
我可以知道为什么会发生这种情况吗
因为 Python 开发人员选择这样做。
请参阅文档 https://docs.python.org/3/library/sys.html#sys.stdout:
在 Windows 上,UTF-8 用于控制台设备。非字符设备(例如磁盘文件和管道)使用系统区域设置编码(即 ANSI 代码页)。
我应该怎么做才能使重定向时默认编码为utf-8?
强制编码。
我已将以下内容添加到受此问题困扰的程序中:
if os.name == "nt":
sys.stdout.reconfigure(encoding="utf-8")
如果你使用stderr
,您可能也想重新配置它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)