如何在管道中使用`subprocess`命令 [英] How to use `subprocess` command with pipes
问题描述
我想使用 subprocess.check_output()
和 ps -A |grep 'process_name'
.我尝试了各种解决方案,但到目前为止没有任何效果.有人可以指导我怎么做吗?
要使用带有 subprocess
模块的管道,您必须传递 shell=True
.>
然而,出于各种原因,这并不是真正可取的,其中最重要的是安全性.相反,分别创建 ps
和 grep
进程,并将输出从一个进程传送到另一个进程,如下所示:
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屋!