python - How to use `subprocess` command with pipes

ID : 10219

viewed : 40

Tags : pythonlinuxsubprocesspipepython

Top 5 Answer for python - How to use `subprocess` command with pipes

vote vote


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.

vote vote


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.

vote vote


See the documentation on setting up a pipeline using 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] 
vote vote



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


You can try the pipe functionality in

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

Top 3 video Explaining python - How to use `subprocess` command with pipes