Shell piping with subprocess in Python

2019-04-21 09:03发布

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:

  1. Run shell command command_1. Collect the output in variable result_1

  2. Shell pipe result_1 into command_2 and collect the output on result_2. In other words, run command_1 | command_2 using the result that I obtained when running command_1 in the step before

  3. Do the same piping result_1 into a third command command_3 and collecting the result in result_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?

1条回答
Rolldiameter
2楼-- · 2019-04-21 09:07

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.

查看更多
登录 后发表回答