我阅读了在 StackOverflow 上找到的关于使用 Python 调用 shell 命令的所有线程subprocess
,但我找不到适用于我的情况的答案:
我想从 Python 中执行以下操作:
运行外壳命令command_1
。收集变量中的输出result_1
壳管 result_1
into command_2
并收集输出result_2
。换句话说,运行command_1 | command_2
使用结果我在跑步时获得的command_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()
而不是带管道的线。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)