Python中带子流程的Shell管道
在使用Python中带子流程的Shell管道,python,shell,subprocess,pipe,Python,Shell,Subprocess,Pipe,在使用子流程调用Python中的shell命令时,我阅读了在StackOverflow上找到的每个线程,但我找不到适用于以下情况的答案: 我想从Python中执行以下操作: 运行shell命令命令\u 1。在变量result\u 1中收集输出 壳管result_1进入命令_2并在result_2上收集输出。换句话说,使用我在前面步骤中运行command\u 1时获得的结果运行command\u 1 将相同的管道result_1导入第三个命令command_3,并在result_3中收集结果 到目
子流程调用Python中的shell命令时,我阅读了在StackOverflow上找到的每个线程,但我找不到适用于以下情况的答案:
我想从Python中执行以下操作:
运行shell命令命令\u 1
。在变量result\u 1中收集输出
壳管result_1
进入命令_2
并在result_2
上收集输出。换句话说,使用我在前面步骤中运行command\u 1
时获得的结果运行command\u 1
将相同的管道result_1
导入第三个命令command_3
,并在result_3
中收集结果
到目前为止,我已经尝试:
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()
而不是带管道的行。有关正确的方法,请参阅。谢谢@SvenMarnach,这是否仍然允许我在Python变量中收集第一个命令的输出?这看起来很棒。如果我想将result\u 1
再次传输到另一个命令,上述内容将如何更改?此时result\u 1
是一个字符串。您应该能够使用新命令重复相同的3行。