在将代码从Python 2移植到Python 3时,我在从标准输入读取UTF-8文本时遇到了这个问题。在Python 2中,这很好:
for line in sys.stdin:
...
但是Python 3期望ASCII从sys.stdin,如果输入中有非ASCII字符,则会得到错误:
UnicodeDecodeError: 'ascii' codec can't decode byte .. in position ..: ordinal not in range(128)
对于常规文件,我将在打开文件时指定编码:
with open('filename', 'r', encoding='utf-8') as file:
for line in file:
...
但是,如何为标准输入指定编码呢?其他这样的帖子建议使用
input_stream = codecs.getreader('utf-8')(sys.stdin)
for line in input_stream:
...
但是,这在Python 3中不起作用,我仍然收到相同的错误消息。我使用的是Ubuntu12.04.2,我的地区设置为en[医]US.UTF-8。
发布于 2018-01-17 14:47:52
import io
import sys
input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
或者,设置PYTHONIOENCODING
环境变量到运行python时所需的编解码器。
https://stackoverflow.com/questions/-100004133
复制相似问题