如何自动将相同的答案传递给 subprocess.Popen?

How to pass the same answer to subprocess.Popen automatically?

我想调用 yes "y" | foo bar,但使用 subprocess.Popen。目前我使用这个:

yes = subprocess.Popen(['yes', '""'], stdout=subprocess.PIPE)
proc = subprocess.Popen(['foo', 'bar'], stdin=yes.stdout, stdout=subprocess.PIPE)

但是,当然,这不适用于 Windows。我该怎么做才能在所有平台上运行?

p = subprocess.Popen(['/bin/cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE )
p.stdin.write("yes\nyes\nyes")

In [18]: p.communicate()
Out[18]: ('yes\nyes\nyes', None)

您当然可以在两个线程中执行此操作(在一个线程中写入,Popen 在另一个线程中读取实例)。

然而,这并不是很安全:

Can someone explain pipe buffer deadlock?

To emulate a shell pipeline yes "y" | foo bar in Python:

#!/usr/bin/env python
from subprocess import Popen, PIPE

foo_proc = Popen(['foo', 'bar'], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin)
foo_output = foo_proc.communicate()[0]
yes_proc.wait() # avoid zombies

要在 Python 中通过管道输入(没有 yes 实用程序),您可以使用 or async. I/O,其中 input_iteratoritertools.repeat(b'y' + os.linesep.encode())