【发布时间】:2013-05-09 02:20:01
【问题描述】:
在将代码从 Python 2 移植到 Python 3 时,我在从标准输入读取 UTF-8 文本时遇到了这个问题。在 Python 2 中,这很好用:
for line in sys.stdin:
...
但是 Python 3 需要来自 sys.stdin 的 ASCII,如果输入中有非 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:
...
但是如何指定标准输入的编码呢?其他 SO 帖子(例如 How to change the stdin encoding on python)建议使用
input_stream = codecs.getreader('utf-8')(sys.stdin)
for line in input_stream:
...
但是,这在 Python 3 中不起作用。我仍然收到相同的错误消息。我使用的是 Ubuntu 12.04.2,我的语言环境设置为 en_US.UTF-8。
【问题讨论】:
-
@RaymondHettinger 鉴于 Python 2 和 Python 3 在这里有非常不同的答案,这些不是重复的问题。重复的问题会有相同的答案。
标签: python python-3.x unicode encoding stdin