Coder Perfect

How to use the command’subprocess’ with pipes


I want to use ps -A | grep ‘process name’ with subprocess.check output(). I tried a few different things, but nothing has worked thus far. Could someone please show me how to accomplish it?

Asked by zuberuber

Solution #1

Shell=True is required to use a pipe with the subprocess module.

However, for a variety of reasons, not least of which being security, this isn’t really a good idea. Rather, separate the ps and grep processes and pipe the output from one to the other, as follows:

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

However, in your instance, calling subprocess is the straightforward solution. str.find on the output after check output((‘ps’, ‘-A’)

Answered by Taymon

Solution #2

You can also communicate with the subprocess objects using the communicate method.

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]

The communicate method returns a tuple of the standard output and the standard error.

Answered by jkalivas

Solution #3

See for information on how to set up a pipeline with subprocess.

I haven’t tested the following code example but it should be roughly what you want:

query = "process_name"
ps_process = Popen(["ps", "-A"], stdout=PIPE)
grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep_process exits.
output = grep_process.communicate()[0]

Answered by AlcubierreDrive

Solution #4


import subprocess

ps =['ps', '-A'], check=True, capture_output=True)
processNames =['grep', 'process_name'],
                              input=ps.stdout, capture_output=True)

Answered by anaken78

Solution #5

In, you may try out the pipe functionality:

import sh
print sh.grep("-ax"), "process_name")

Answered by amoffat

Post is based on