首页 > 解决方案 > 尝试将 Python UTF-8 标准输出重定向到 Windows 上的文件时发生错误

问题描述

当我尝试通过运行在 Powershell 中重定向 UTF-8 标准输出时python3 .\test.py > test.txt,会发生错误:

UnicodeEncodeError:“charmap”编解码器无法对位置 0-1 中的字符进行编码:字符映射到 <undefined>

中的代码test.py如下,由 UTF-8 编码。

print("\u2714")

代码在这里上传。 https://github.com/lingsongfeng/pytest

标签: pythonwindowspowershell

解决方案


重定向 I/O 时,Python 使用 Windows 的默认编码(cp1252对于美国 Windows),但如果您想覆盖它,它将查看环境变量:

C:\> set PYTHONIOENCODING=utf8
C:\> test.py > out.txt

最近,set PYTHONUTF8=1还将使 Python 默认使用 UTF-8 进行文件和 I/O 重定向。


推荐阅读