linux - [Solved-5 Solutions] Python subprocess command with pipe - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
How to use python subprocess command with pipe ?
Linux - Solution 1:
- To use a pipe with the subprocess module, you have to pass shell=True.
- It 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()
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 2:
You can use method on 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
click below button to copy the code. By - Linux tutorial - team
This method returns in a tuple the standard output and the standard error
Linux - Solution 3:
setting up a pipeline using subprocess:
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]
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 4:
To use 'pgrep' command instead of 'ps -A | grep 'process_name'
Linux - Solution 5:
You can try the pipe functionality in sh.py:
import sh
print sh.grep(sh.ps("-ax"), "process_name")