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:
instead of the line with the pipe.