在Python中使用子流程进行Shell管道 [英] Shell piping with subprocess in Python

查看:73
本文介绍了在Python中使用子流程进行Shell管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用subprocess从Python调用Shell命令时,我读取了我在StackOverflow上找到的每个线程,但是我找不到适用于我的情况的答案:

我想在Python中执行以下操作:

  1. 运行shell命令command_1.将输出收集在变量result_1

  2. Shell管道 result_1进入command_2,并在result_2上收集输出.换句话说,使用在上一步中运行command_1 时获得的结果,运行command_1 | command_2

  3. 对第三个命令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:

  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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆