python - 尝试将 Python UTF-8 标准输出重定向到 Windows 上的文件时发生错误
问题描述
当我尝试通过运行在 Powershell 中重定向 UTF-8 标准输出时python3 .\test.py > test.txt
,会发生错误:
UnicodeEncodeError:“charmap”编解码器无法对位置 0-1 中的字符进行编码:字符映射到 <undefined>
中的代码test.py
如下,由 UTF-8 编码。
print("\u2714")
解决方案
重定向 I/O 时,Python 使用 Windows 的默认编码(cp1252
对于美国 Windows),但如果您想覆盖它,它将查看环境变量:
C:\> set PYTHONIOENCODING=utf8
C:\> test.py > out.txt
最近,set PYTHONUTF8=1
还将使 Python 默认使用 UTF-8 进行文件和 I/O 重定向。
推荐阅读
- python - 删除不同时间分辨率的天列表(分钟数据)
- python - Visual Studio Code:编辑源代码编号并除以二的自定义快捷方式
- vim - 神秘的vim上下文弹出:它来自哪里,我该如何摆脱它?
- ruby - 打包一个 Git Gem 以部署到 Ruby Lambda 运行时
- java - Java:使用扫描仪根据用户输入构造二维矩阵数组
- php - file_put_contents 通过 PHP 中的 API 上传多张图片
- amazon-web-services - Ec2 通过 AMI、DNS 和 SSL 自动化
- boost - 修改 BOOST_PP_SEQ
- python - 在 pandas.period 中计算四分之一长度
- javascript - 如何将 API 调用的结果设置为 Recoil atom 的默认值?