command - How to run " ps cax | grep something " in Python? -
how run command pipe |
in it?
the subprocess module seems complex...
is there like
output,error = `ps cax | grep something`
as in shell script?
import subprocess import shlex proc1 = subprocess.popen(shlex.split('ps cat'),stdout=subprocess.pipe) proc2 = subprocess.popen(shlex.split('grep python'),stdin=proc1.stdout, stdout=subprocess.pipe,stderr=subprocess.pipe) proc1.stdout.close() # allow proc1 receive sigpipe if proc2 exits. out,err=proc2.communicate() print('out: {0}'.format(out)) print('err: {0}'.format(err))
ps. using shell=true
can dangerous. see example the warning in docs.
there sh module can make subprocess scripting in python lot more pleasant:
import sh print(sh.grep(sh.ps("cax"), 'something'))
Comments
Post a Comment