在Python中使用子流程进行Shell管道 [英] Shell piping with subprocess in Python
问题描述
当我使用subprocess
从Python调用Shell命令时,我读取了我在StackOverflow上找到的每个线程,但是我找不到适用于我的情况的答案:
我想在Python中执行以下操作:
-
运行shell命令
command_1
.将输出收集在变量result_1
中
-
Shell管道
result_1
进入command_2
,并在result_2
上收集输出.换句话说,使用在上一步中运行command_1
时获得的结果,运行command_1 | command_2
-
对第三个命令
command_3
执行相同的配管result_1
,并将结果收集在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()
代替管道的线段.
I read every thread I found on StackOverflow on invoking shell commands from Python using subprocess
, but I couldn't find an answer that applies to my situation below:
I would like to do the following from Python:
Run shell command
command_1
. Collect the output in variableresult_1
Shell pipe
result_1
intocommand_2
and collect the output onresult_2
. In other words, runcommand_1 | command_2
using the result that I obtained when runningcommand_1
in the step beforeDo the same piping
result_1
into a third commandcommand_3
and collecting the result inresult_3
.
So far I have tried:
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();
the reason seems to be that "echo " + result_1
does not simulate the process of obtaining the output of a command for piping.
Is this at all possible using subprocess? If so, how?
You can do:
pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE)
pipe.stdin.write(result_1)
pipe.communicate()
instead of the line with the pipe.
这篇关于在Python中使用子流程进行Shell管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!