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

rickylf2lee 回答:Python 3.8 Windows:管道打印时,打印会产生UnicodeEncodeError

添加

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,and the Windows console

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

本文链接:https://www.f2er.com/3070980.html

大家都在问