Home:ALL Converter>Issue in running system commands from python script continuously?

Issue in running system commands from python script continuously?

Ask Time:2013-01-24T14:14:18         Author:kelvin

Json Formatter

I have a python script that checks continuously for snmpd and a socket script to be running .If any of these get killed it should kill both and start new session. The problem is once socket is running it wait for connection for long ,in between if anyone kill snmpd its not getting started (think its not going to loop back).What may be the reason and a possible solution.? any optimisation possible for the code?

def terminator():
    i=0
    j=0
    os.system("ps -eaf|grep snmpd|cut -d \" \" -f7 >snmpd_pid.txt")
    os.system("ps -eaf|grep iperf|cut -d \" \" -f7 >iperf_pid.txt")
    os.system("ps -eaf|grep sock_bg.py|cut -d \" \" -f7 >script_pid.txt")
    snmpd_pids = tuple(line.strip() for line in open('snmpd_pid.txt'))
    iperf_pids = tuple(line.strip() for line in open('iperf_pid.txt'))
    script_pids = tuple(line.strip() for line in open('script_pid.txt'))
    k1 = len(snmpd_pids) - 2
    k2 = len(iperf_pids) - 2
    k3 = len(script_pids) - 2
    if (k1 == 0 or k3 == 0):
        for i in range(k1):
            cmd = 'kill -9 %s' %(snmpd_pids[i])
            os.system(cmd)
        for i in range(k2):
            cmd = 'kill -9 %s' %(iperf_pids[i])
            os.system(cmd)
        for i in range(k3):
            cmd = 'kill -9 %s' %(script_pids[i])
            os.system(cmd)
    os.system("/usr/local/sbin/snmpd -f -L -d -p 9999")
    os.system("python /home/maxuser/utils/python-bg/sock_bg.py")
try:
    terminator()
except:
    print 'an exception occured'

Author:kelvin,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/14495073/issue-in-running-system-commands-from-python-script-continuously
yy