python - Python 3.8 Windows:管道时打印产生 UnicodeEncodeError
问题描述
尽管 Python 3.8 也应该在 Windows 上使用 UTF-8 ( PEP-0528 PEP-0529 ),但仍然可以
UnicodeEncodeError: 'charmap' codec can't encode character '\u251c' in position 0: character maps to <undefined>
异常发生在cp1252.py
.
示例代码(t.py
):
print(b'\xe2\x94\x9c'.decode('utf-8'))
print(b'\xe2\x94\x94'.decode('utf-8'))
print(b'\xe2\x94\x80'.decode('utf-8'))
print(b'\xe2\x94\x82'.decode('utf-8'))
不会发生python t.py
,但在管道时会发生
python t.py | python -c "import sys; print(sys.stdin.read())"
或转发到文件 ( python t.py > t.txt
)。
解决方案
添加
import sys
import codecs
try:
sys.stdin = codecs.getreader("utf-8")(sys.stdin.detach())
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
except:
pass
print(b'\xe2\x94\x9c'.decode('utf-8'))
从这篇文章后面的答案之一有助于:
try-except 在使用 py.test 时很有用,因为与 py.test capsys 存在冲突,导致替换sys.stdout
失败。
推荐阅读
- algorithm - 计算特定算法的大O复杂度
- javascript - 无论如何要替换一些块数据来添加图像?
- java - 如何使用Java从字符串“automation130214141113(订单#2882649)”中提取子字符串“2882649”
- sql - 在 PostgreSQL 或 SQL 中是否可以将值列表转储到单个列中?
- php - 尝试使用 PHP 从 IOT 获取数据
- php - 不能跨页面携带 SESSION 变量
- c - 第一次使用线程
- c# - 相当于实体框架中的“SELECT NULL AS ColumnName”
- regex - 获取单词上方行中的值
- sql - SQL - 而不是 INSERT 和临时变量