[python] How to use `subprocess` command with pipes

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?

This question is related to python linux subprocess pipe

The answer is


Or you can always use the communicate method on the subprocess objects.

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.


command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

See the documentation on setting up a pipeline using subprocess: http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

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]

JKALAVIS solution is good, however I would add an improvement to use shlex instead of SHELL=TRUE. below im grepping out Query times

#!/bin/python
import subprocess
import shlex

cmd = "dig @8.8.4.4 +notcp www.google.com|grep 'Query'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

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)

Also, try to use 'pgrep' command instead of 'ps -A | grep 'process_name'


After Python 3.5 you can also use:

    import subprocess

    f = open('test.txt', 'w')
    process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
    f.write(process.stdout)
    f.close()

The execution of the command is blocking and the output will be in process.stdout.


You can try the pipe functionality in sh.py:

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to subprocess

Subprocess check_output returned non-zero exit status 1 OSError: [Errno 8] Exec format error OSError: [WinError 193] %1 is not a valid Win32 application How to catch exception output from Python subprocess.check_output()? Subprocess changing directory OSError: [Errno 2] No such file or directory while using python subprocess in Django live output from subprocess command running multiple bash commands with subprocess Understanding Popen.communicate wait process until all subprocess finish?

Examples related to pipe

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Using Pipes within ngModel on INPUT Elements in Angular What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe Pass a password to ssh in pure bash How to open every file in a folder Why does cURL return error "(23) Failed writing body"? How do I use a pipe to redirect the output of one command to the input of another? How to use `subprocess` command with pipes Pipe subprocess standard output to a variable