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

2024-04-26 05:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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]

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

p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)

如何向进程提供输入字符串? 如果我尝试将最后一行改为:

output = p2.communicate(input=inputstring)[0]

这不管用。

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

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()

我希望我说得够清楚了,谢谢你的帮助。


Tags: 命令示例inputoutput进程stdinstdoutgrep
3条回答

我假设catgrep只是示例命令,否则您可以使用没有子进程的纯Python解决方案,例如:

for line in simple.splitlines():
    if "line" in line:
       print(line)

或者如果要使用grep

from subprocess import Popen, PIPE

output = Popen(['grep', 'line'], stdin=PIPE, stdout=PIPE).communicate(simple)[0]
print output,

您可以将第一个命令的输出传递给第二个命令,而不必首先将其存储在字符串中:

from subprocess import Popen, PIPE
from threading import Thread

# start commands in parallel
first = Popen(first_command, stdin=PIPE, stdout=PIPE)
second = Popen(second_command, stdin=first.stdout, stdout=PIPE)
first.stdout.close() # notify `first` if `second` exits 
first.stdout = None # avoid I/O on it in `.communicate()`

# feed input to the first command
Thread(target=first.communicate, args=[simple]).start() # avoid blocking

# get output from the second command at the same time
output = second.communicate()[0]
print output,

如果您不想将所有的输入/输出存储在内存中,则可能需要线程(在块中读/写而不阻塞)或select循环(在POSIX上工作)。

如果有多个命令,那么按照@Troels Folke的建议直接使用shell或使用a library such as ^{} that hides all the gory details of emulating the shell by hand可能更容易阅读。

如果你这样做了

from subprocess import Popen, PIPE
p1 = Popen(["cat"], stdout=PIPE, stdin=PIPE)

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

已经给出的程序是绝对好的,似乎没有问题。

嗯,为什么不掺一点呢?:-)

from subprocess import Popen, PIPE
cproc = Popen('cat | grep line', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
out, err = cproc.communicate("this line has the word line in it")

但要注意:

  • 这只适用于使用Bourne Shell兼容Shell的系统(与大多数*nix'es一样)

  • Usign shell=True并将用户输入放在命令字符串中是一个坏主意,除非首先转义用户输入。阅读子流程文档->;“常用参数”了解详细信息。

  • 这是丑陋的,不可携带的,非Python等。。。

编辑: 不过,如果您只想使用grep,则无需使用cat。只需将输入直接提供给grep,或者更好地使用python正则表达式。

相关问题 更多 >

    热门问题