<p>无论何时发生重定向或管道,标准输入流都将设置为该值。所以你可以直接从<a href="https://docs.python.org/2/library/sys.html#sys.stdin" rel="nofollow noreferrer">^{<cd1>}</a>读取,就像这样</p>
<pre><code>import sys
for line in sys.stdin:
process_line(line)
</code></pre>
<p>如果缓冲占用了您的时间,您可以调整/禁用输入缓冲,如<a href="https://stackoverflow.com/a/3670470/1903116">this answer</a>中所述</p>
<p><strong>减小缓冲区大小:</strong></p>
<pre><code>import os
import sys
for line in os.fdopen(sys.stdin.fileno(), 'r', 100):
process_line(line)
</code></pre>
<p>现在它最多只能缓冲100个字节</p>
<p><strong>禁用缓冲:</strong></p>
<p>引用官方文件</p>
<p><strong><a href="https://docs.python.org/2/using/cmdline.html#cmdoption-u" rel="nofollow noreferrer">^{<cd2>}</a></strong></p>
<blockquote>
<p>Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.</p>
<p>Note that there is internal buffering in <code>file.readlines()</code> and File Objects (<code>for line in sys.stdin</code>) which is not influenced by this option. To work around this, you will want to use <code>file.readline()</code> inside a <code>while 1: loop</code>.</p>
</blockquote>