Coder Perfect

How to use the command’subprocess’ with pipes

Problem

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)
ps.wait()

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]
print(output)

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

Answered by jkalivas

Solution #3

See http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline 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

Using subprocess.run

import subprocess

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

Answered by anaken78

Solution #5

In sh.py, you may try out the pipe functionality:

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

Answered by amoffat

Post is based on https://stackoverflow.com/questions/13332268/how-to-use-subprocess-command-with-pipes