壳牌管道可以用Python

壳牌管道可以用Python

问题描述:

我读的每个线程我在计算器上发现使用subprocess从Python中调用shell命令,但我找不到适用于我的情况如下答案子:壳牌管道可以用Python

我想这样做来自Python的以下内容:

  1. 运行shell命令command_1。收集输出在可变result_1

  2. 壳管result_1command_2并收集result_2的输出。换句话说,使用我运行当在步骤command_1之前

  3. 照此管道result_1到第三命令command_3result_3收集结果而获得的结果运行command_1 | command_2

到目前为止,我曾尝试:

p = subprocess.Popen(command_1, stdout=subprocess.PIPE, shell=True) 

result_1 = p.stdout.read(); 

p = subprocess.Popen("echo " + result_1 + ' | ' + 
command_2, stdout=subprocess.PIPE, shell=True) 

result_2 = p.stdout.read(); 

的原因似乎是"echo " + result_1不模拟获得命令的输出管道的过程。

这是所有可能的使用子进程?如果是这样,怎么样?

+2

请参阅[本文档中的示例](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline)以获取正确的方法。 – 2012-03-03 01:00:34

+1

谢谢@SvenMarnach,那还能让我收集Python变量中第一条命令的输出吗? – 2012-03-03 01:03:52

你可以这样做:

pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE) 
pipe.stdin.write(result_1) 
pipe.communicate() 

,而不是与管道线路。

+0

这看起来不错。如果我想将'result_1' *再次*传递给另一个命令,上述更改将如何? – 2012-03-03 01:46:46

+1

那时''result_1'是一个字符串。你应该可以用新命令重复相同的3行。 – 2012-03-04 06:21:58