你想要的这里是(显然)系列管道:
com[0] | com[1] | ... | com[n-1]
最简单的方法,如果你不担心“坏”字和炮弹,是刚刚加入他们所有成一个大的shell命令:
p = subprocess.Popen(' | '.join(' '.join(words) for words in com), shell=True, ...)
另外,既然你想标准输出=无最初,你可以用@简单地具有p的PST的惯用伎俩最初与无的.stdout任何对象。但是你也应该注意到你依赖于系统来关闭你之前的每个子进程.Popen()(因此它们的输出管道在循环内部是close()d),这与CPython一起发生,但不与Jython一起发生(据我了解 - 我没有实际使用过Jython)。所以,你可能需要一个更明确的循环:
# assumes len(com) >= 1
p0 = subprocess.Popen(com[0], stdout=subprocess.PIPE)
# don't use stderr=subprocess.PIPE -- if you want stderr to be piped too
# use stderr=subprocess.STDOUT, or create a stderr pipe early manually and
# supply the fd directly; see hints in text below.
for words in com[1:]:
p1 = subprocess.Popen(words, stdin=p0.stdout, stdout=subprocess.PIPE)
# again you don't want to set stderr to subprocess.PIPE here
p0.stdout.close() # now that it's going to p1, we must ditch ours
p0 = p1 # p1 becomes the input to any new p1 we create next time
# at this point, use p0.communicate() to read output
如果您重定向标准错误= subprocess.STDOUT每个POPEN(),这将管道从每个子命令输出的错误到下一个。要将它们全部传送到您的程序中,您必须首先创建一个OS级别的管道对象,然后将每个管道连接到该(单个)管道的写入端,然后绕过子进程模块以获取指向它的“最终”子进程对象,因此它的选择/轮询代码将从该管道中吸取任何数据。 (由于subprocess.communicate()将只读多从两个这样的管道,你不能独立捕获每个单独的子命令的stderr输出。)
注:以上都不是测试...
*嘎嘎庸医!*在这个例子中,它不*必须是'Popen'对象;只是一个对象有一个合适的'stdout' ..(不,从一个系统/操作系统的角度来看,一个“空”Popen没什么意义[在大多数情况下] :-) – 2012-03-08 08:55:08
好吧,似乎更多的工作来创建一个类与仅创建虚拟Popen对象相比,它是一个stdout def。不知道什么是最正确的方式。 – 2012-03-08 10:23:30