<p>对于您的用例来说,管道似乎是一个合适的选择。注意,在正常情况下,读写端都期望数据被写入或消耗。还要确保缓冲区不会让您感到意外(没有任何东西通过,因为除非相应地设置,否则缓冲区不会自动刷新,除非在预期的边界上)。在</p>
<p>两个管道(它们是单向的)如何在两个进程之间使用的一个基本示例:</p>
<pre><code>import os
def child():
"""
This function is executed in a child process.
"""
infile = os.fdopen(r1)
outfile = os.fdopen(w2, 'w', buffering=1)
for line in infile:
if line.rstrip() == 'quit':
break
outfile.write(line.upper())
def parent():
"""
This function is executed in a parent process.
"""
outfile = os.fdopen(w1, 'w', buffering=1)
infile = os.fdopen(r2)
print('Foo', file=outfile)
print(infile.readline(), end='')
print('bar', file=outfile)
print(infile.readline(), end='')
print('quit', file=outfile)
(r1, w1) = os.pipe() # for parent -> child writes
(r2, w2) = os.pipe() # for child -> parent writes
pid = os.fork()
if pid == 0:
child() # child code runs here.
elif pid > 0:
parent() # parent code runs here.
os.waitpid(pid, 0) # wait for child
else:
raise RuntimeError("This should not have happened.")
# Once returned from corresponding function, both processes exit
</code></pre>
<p>实际上,使用<code>subprocess</code>会更容易、更实用,而且您可能希望<code>exec</code>另一个二进制文件。前者需要被告知不要关闭(至少是相关的管道)文件描述符,后者需要管道文件描述符是可继承的(没有设置<code>O_CLOEXEC</code>标志)。否则同上。在</p>
<p>子代码:</p>
^{pr2}$
<p>父脚本:</p>
<pre><code>import os
import subprocess
(r1, w1) = os.pipe2(0) # for parent -> child writes
(r2, w2) = os.pipe2(0) # for child -> parent writes
child = subprocess.Popen(['./child.py', str(r1), str(w2)], pass_fds=(r1, w2))
outfile = os.fdopen(w1, 'w', buffering=1)
infile = os.fdopen(r2)
print('Foo', file=outfile)
print(infile.readline(), end='')
print('bar', file=outfile)
print(infile.readline(), end='')
print('quit', file=outfile)
child.wait()
</code></pre>
<p>想想看,我忘了问,孩子是需要stdin/out来做什么,还是可以用它来获取信息。那就更简单了:</p>
<p>儿童:</p>
<pre><code>import sys
for line in sys.stdin:
if line.rstrip() == 'quit':
break
print(line.upper(), end='', flush=True)
</code></pre>
<p>家长:</p>
<pre><code>import os
import subprocess
(r1, w1) = os.pipe2(0) # for parent -> child writes
(r2, w2) = os.pipe2(0) # for child -> parent writes
child = subprocess.Popen(['./child.py'], stdin=r1, stdout=w2)
outfile = os.fdopen(w1, 'w', buffering=1)
infile = os.fdopen(r2)
print('Foo', file=outfile)
print(infile.readline(), end='')
print('bar', file=outfile)
print(infile.readline(), end='')
print('quit', file=outfile)
child.wait()
</code></pre>
<p>如前所述,它并不是真正针对python的,这些只是关于如何使用管道作为一个选项的粗略提示。在</p>