如何从stdin读取输入并强制执行编码?

时间:2017-11-22 02:01:02

标签: python file utf-8 io stdin

目标是不断阅读stdin并在Python2和Python3中强制执行utf8

我尝试过以下解决方案:

我试过了:

#!/usr/bin/env python

from __future__ import print_function, unicode_literals
import io
import sys

# Supports Python2 read from stdin and Python3 read from stdin.buffer
# https://stackoverflow.com/a/23932488/610569
user_input = getattr(sys.stdin, 'buffer', sys.stdin)


# Enforcing utf-8 in Python3
# https://stackoverflow.com/a/16549381/610569
with io.TextIOWrapper(user_input, encoding='utf-8') as fin:
    for line in fin:
        # Reads the input line by line
        # and do something, for e.g. just print line.
        print(line)

代码在Python3中工作,但在Python2中,TextIOWrapper没有读取函数,它会抛出:

Traceback (most recent call last):
  File "testfin.py", line 12, in <module>
    with io.TextIOWrapper(user_input, encoding='utf-8') as fin:
AttributeError: 'file' object has no attribute 'readable'

那是因为在Python中user_input,即sys.stdin.buffer是一个 _io.BufferedReader对象及其属性有readable

<class '_io.BufferedReader'>

['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_dealloc_warn', '_finalizing', 'close', 'closed', 'detach', 'fileno', 'flush', 'isatty', 'mode', 'name', 'peek', 'raw', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

在Python2中,user_input是一个文件对象,其属性没有readable

<type 'file'>

['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

1 个答案:

答案 0 :(得分:1)

如果您不需要完全成熟的io.TextIOWrapper,而只需要一个解码的流进行阅读,您可以使用codecs.getreader()创建解码包装器:

reader = codecs.getreader('utf8')(user_input)
for line in reader:
    # do whatever you need...
    print(line)

codecs.getreader('utf8')codecs.StreamReader创建工厂,然后使用原始流进行实例化。 我不确定StreamReader是否支持with上下文,但这可能不是绝对必要的(读取后不需要关闭STDIN,我猜......)。

在底层流只提供非常有限的接口的情况下,我已成功使用此解决方案。

更新(第2版)

从评论中可以清楚地看到,您实际上需要io.TextIOWrapper在交互模式下拥有正确的线路缓冲等; codecs.StreamReader仅适用于管道输入等。

使用this answer,我能够正确地进行交互式输入:

#!/usr/bin/env python
# coding: utf8

from __future__ import print_function, unicode_literals
import io
import sys

user_input = getattr(sys.stdin, 'buffer', sys.stdin)

with io.open(user_input.fileno(), encoding='utf8') as f:
    for line in f:
        # do whatever you need...
        print(line)

这将从二进制STDIN缓冲区创建一个带有强制编码的io.TextIOWrapper