在将代码从Python 2移植到Python 3时,我在从标准输入读取UTF-8文本时遇到了这个问题.在Python2中,这很好:
for line in sys.stdin:
...
但是Python 3期望ASCII从sys.stdin开始,如果输入中有非ASCII字符,我会得到错误:
UnicodeDecodeError:"ascii"编解码器无法解码字节..就位序号不在范围内(128)
对于常规文件,我会在打开文件时指定编码:
with open('filename', 'r', encoding='utf-8') as file:
for line in file:
...
但是我如何为标准输入指定编码呢?其他SO帖子(如How to change the stdin encoding on python)建议使用
input_stream = codecs.getreader('utf-8')(sys.stdin)
for line in input_stream:
...
然而,这在Python3中不起作用.我仍然收到相同的错误消息.我正在使用Ubuntu12.04.2,我的语言环境设置为en_US.UTF-8.