<p>对于您的特定情况,如果您只为单个标准句柄传递了<code>subprocess.PIPE</code>(在您的例子中,<code>stdin</code>),那么在您的示例中,您可以安全地反复调用<code>sorter.stdin.write(line)</code>。完成输出写入后,调用<code>sorter.stdin.close()</code>以便<code>sort</code>知道输入已完成,并且它可以执行实际的排序和输出工作(<code>sorter.communicate()</code>可能也可以工作;否则,在关闭<code>stdin</code>之后,您可能需要调用<code>sorter.wait()</code>让它完成)。在</p>
<p>如果需要处理多个管道标准句柄,正确的方法是使用<a href="https://docs.python.org/3/library/threading.html" rel="nofollow">^{<cd9>}</a>为每个必须在第一个之外处理的管道指定一个线程(概念上相对简单,但是很重,并且引入了线程的所有麻烦),或者使用<a href="https://docs.python.org/3/library/select.html" rel="nofollow">^{<cd10>}</a>模块(或者在python3.4+中,<a href="https://docs.python.org/3/library/selectors.html" rel="nofollow">^{<cd11>}</a>模块),这是相当棘手的,但可以(在某些情况下)更有效。最后,还有一个<a href="https://docs.python.org/3/library/tempfile.html" rel="nofollow">creating temporary files for output</a>,因此可以在进程写入文件时直接写入进程的{<cd2>};然后可以在空闲时读取文件(注意,在退出之前,子进程不必刷新自己的输出缓冲区,因此输出可能不会立即响应您的输入到达进一步的输入和输出已经填充并刷新了缓冲区)。在</p>
<p><code>subprocess.Popen</code>的<code>.communicate()</code>方法使用线程或<code>select</code>模块原语本身(取决于操作系统支持;实现在<a href="https://hg.python.org/cpython/file/default/Lib/subprocess.py" rel="nofollow">various ^{<cd16>} methods here</a>下)每当您为一个以上的标准句柄传递<code>subprocess.PIPE</code>;这就是您必须这样做的方式。在</p>