我正在尝试使用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()
我希望我说得够清楚了,谢谢你的帮助。
我假设
cat
,grep
只是示例命令,否则您可以使用没有子进程的纯Python解决方案,例如:或者如果要使用
grep
:您可以将第一个命令的输出传递给第二个命令,而不必首先将其存储在字符串中:
如果您不想将所有的输入/输出存储在内存中,则可能需要线程(在块中读/写而不阻塞)或select循环(在POSIX上工作)。
如果有多个命令,那么按照@Troels Folke的建议直接使用shell或使用a library such as ^{} that hides all the gory details of emulating the shell by hand 可能更容易阅读。
如果你这样做了
你应该做
p1.communicate("Your Input to the p1")
,这将流经管道。 stdin是进程的输入,您应该只与它通信。已经给出的程序是绝对好的,似乎没有问题。
嗯,为什么不掺一点呢?:-)
但要注意:
这只适用于使用Bourne Shell兼容Shell的系统(与大多数*nix'es一样)
Usign shell=True并将用户输入放在命令字符串中是一个坏主意,除非首先转义用户输入。阅读子流程文档->;“常用参数”了解详细信息。
这是丑陋的,不可携带的,非Python等。。。
编辑: 不过,如果您只想使用
grep
,则无需使用cat
。只需将输入直接提供给grep,或者更好地使用python正则表达式。相关问题 更多 >
编程相关推荐