Python子进程模块,如何为第一个管道命令系列提供输入?

Pla*_*lan 5 python subprocess pipe

我正在尝试使用Python的子进程模块.我需要的是将输入发送到第一个进程,其输出成为第二个进程的输入.这种情况基本上与这里的文档中给出的示例几乎相同:http: //docs.python.org/library/subprocess.html#replacing-shell-pipeline, 除了我需要提供输入第一个命令.这是复制的示例:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
Run Code Online (Sandbox Code Playgroud)

如果我们将第一行更改为:

p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)
Run Code Online (Sandbox Code Playgroud)

如何为进程提供输入字符串?如果我通过将最后一行更改为:

output = p2.communicate(input=inputstring)[0]
Run Code Online (Sandbox Code Playgroud)

这不起作用.

我有一个工作版本,它只将第一个命令的输出存储在一个字符串中,然后将其传递给第二个命令.这并不可怕,因为基本上没有可以被利用的并发性(在我的实际用例中,第一个命令将很快退出并在最后生成所有输出).这是完整的工作版本:

import subprocess

simple = """Writing some text
with some lines in which the
word line occurs but others
where it does
not
"""

def run ():
  catcommand = [ "cat" ]
  catprocess = subprocess.Popen(catcommand,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
  (catout, caterr) = catprocess.communicate(input=simple)
  grepcommand = [ "grep", "line" ]
  grepprocess = subprocess.Popen(grepcommand,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
  (grepout, greperr) = grepprocess.communicate(input=catout)
  print "--- output ----"
  print grepout 
  print "--- error ----"
  print greperr 

if __name__ == "__main__":
  run()
Run Code Online (Sandbox Code Playgroud)

我希望我已经足够清楚,谢谢你的帮助.

Sen*_*ran 6

如果你这样做

from subprocess import Popen, PIPE
p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)
Run Code Online (Sandbox Code Playgroud)

你应该这样做p1.communicate("Your Input to the p1"),那将流经PIPE.stdin是进程的输入,你应该只与它通信.

给出的程序绝对没问题,似乎没有问题.