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

问题描述

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

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?

推荐答案

要将管道与subprocess模块一起使用,必须传递shell=True.

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

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

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()

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

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

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

07-29 23:42