使用 sys.stdin 获取用户输入数据

Getting user input data using sys.stdin

import sys

data = []
for line in sys.stdin:
    data.append(line)

我没有使用 .read().readline() 但是这段代码可以读取数据。它逐行读取数据。输入数据由 '\n' 分隔。数据由用户键入。像 'input()' .

我的问题:

  1. 不需要.read().readline()吗?
  2. 我想知道为什么 for 循环在 sys.stdin 上工作以及它如何逐行读取数据?

如果您查看 the documentation for sys,您会发现 sys.stdin(和 sys.stdout / sys.stderr)只是文件对象。

These streams are regular text files like those returned by the open() function.

The documentation about open() 说:

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper).

TextIOWrapper 继承自 IOBase,它有一个 __iter__ 方法。此 __iter__ 方法允许循环遍历文件中的行。我找不到在 Python 文档中注明的位置,但给出了 in the source code for IOBase.

IOBase (and its subclasses) support the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream.