i have shell script used run quick process check mechanism in linux environment. below 1 piece of code using.
how can achieve same in python? searched , found use "subprocess" module purpose, enough?
check_ntp () { echo "checking ntp service status on $(uname -n)" ps -e | grep ntp > /dev/null 2>&1 if [ $? -eq 0 ] ; echo "service status: ntp service running" else echo "service status: ntp service not running" fi }
update
i found answer question myself:
#!/usr/bin/python import subprocess psntp = subprocess.call('ps -e| grep ntp > /dev/null 2>&1', shell=true) if psntp == 0: print "status: ntp service running" else: print "status: ntp service not runningg" psnscd = subprocess.call('ps -e | grep nscd > /dev/null 2>&1', shell=true) if psnscd == 0: print "status: nscd service running" else: print "status: nscd service not running"
i couldn't figure out how subprocess.check_output using subprocess.popen may job:
import subprocess cmd1 = ['ps', '-e'] cmd2 = ['grep', 'ntp'] proc1 = subprocess.popen(cmd1,stdout=subprocess.pipe) proc2 = subprocess.popen(cmd2,stdin=proc1.stdout, stdout=subprocess.pipe,stderr=subprocess.pipe) proc1.stdout.close() # allow proc1 receive sigpipe if proc2 exits. out, err=proc2.communicate() if out: print "service status: ntp service running" else: print "service status: ntp service not running" # print('out: {0}'.format(out)) # optionally view output # print('err: {0}'.format(err)) # , errors
Comments
Post a Comment