python - 重定向输出时更改了 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?
谢谢
解决方案
您正在使用 Windows。发生这种情况是因为 Windows 7 控制台不理解 UTF-8。因此,当您显示标准输出时,它需要编码为 Windows 可以显示的内容。
Luciano Ramalho 的书Fluent Python很好地解释了这一点。
推荐阅读
- python-3.x - 是否可以从 BytesIO 对象读取 DICOM 文件?
- android - HTML 代码不包含我想要的字符串
- r - 如何计算 R 中具有不同时间范围和 NA 的时间序列数据的平均值
- vscode-settings - 带有 WSL 的 VS Code 现在打开 browser.sh 文件,而不是启动浏览器
- r - 有条件地将多列中的值替换为一列中的值
- aws-lambda - API 网关代理集成。第二个 lambda 函数的返回响应
- c# - 是否可以在不使用 ArcGIS Pro 的情况下使用 ArcGIS Web 查看 BIM 模型
- html - 兄弟淡入淡出类扩展到容器之外
- java - 在 Spring Boot 中,我们如何通过命令行加载 kafka.bootstrap-servers?
- java - 在 Netty 处理程序中重用 HTTP 响应