壳牌管道可以用Python
我读的每个线程我在计算器上发现使用subprocess
从Python中调用shell命令,但我找不到适用于我的情况如下答案子:壳牌管道可以用Python
我想这样做来自Python的以下内容:
运行shell命令
command_1
。收集输出在可变result_1
壳管
result_1
成command_2
并收集result_2
的输出。换句话说,使用我运行当在步骤command_1
之前照此管道
result_1
到第三命令command_3
和result_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
不模拟获得命令的输出管道的过程。
这是所有可能的使用子进程?如果是这样,怎么样?
你可以这样做:
pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE)
pipe.stdin.write(result_1)
pipe.communicate()
,而不是与管道线路。
这看起来不错。如果我想将'result_1' *再次*传递给另一个命令,上述更改将如何? – 2012-03-03 01:46:46
那时''result_1'是一个字符串。你应该可以用新命令重复相同的3行。 – 2012-03-04 06:21:58
请参阅[本文档中的示例](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline)以获取正确的方法。 – 2012-03-03 01:00:34
谢谢@SvenMarnach,那还能让我收集Python变量中第一条命令的输出吗? – 2012-03-03 01:03:52