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

2024-05-23 11:03:30 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有以下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?
谢谢


Tags: 文件pytestimporttxtstdoutsysout
1条回答
网友
1楼 · 发布于 2024-05-23 11:03:30

你在用窗户。这是因为Windows7控制台不理解UTF-8。因此,当您显示标准输出时,需要将其编码为Windows可以显示的内容。

卢西亚诺·拉马略的书Fluent Python很好地解释了这一点。

相关问题 更多 >

    热门问题