如何在管道中使用`subprocess`命令 [英] How to use `subprocess` command with pipes

查看:25
本文介绍了如何在管道中使用`subprocess`命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 subprocess.check_output()ps -A |grep 'process_name'.我尝试了各种解决方案,但到目前为止没有任何效果.有人可以指导我怎么做吗?

解决方案

要使用带有 subprocess 模块的管道,您必须传递 shell=True.

然而,出于各种原因,这并不是真正可取的,其中最重要的是安全性.相反,分别创建 psgrep 进程,并将输出从一个进程传送到另一个进程,如下所示:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)ps.等待()

然而,在您的特定情况下,简单的解决方案是调用 subprocess.check_output(('ps', '-A')) 然后 str.find在输出上.

I want to use subprocess.check_output() with ps -A | grep 'process_name'. I tried various solutions but so far nothing worked. Can someone guide me how to do it?

解决方案

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

这篇关于如何在管道中使用`subprocess`命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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