首页 > 解决方案 > 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)。

标签: pythonwindowsconsolepython-3.8

解决方案


添加

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'))

从这篇文章后面的答案之一有助于:

Python、Unicode 和 Windows 控制台

try-except 在使用 py.test 时很有用,因为与 py.test capsys 存在冲突,导致替换sys.stdout失败。


推荐阅读