Python用 subprocess编写超时进程控制脚本

来源:互联网 发布:js onload=onload() 编辑:程序博客网 时间:2024/05/21 09:44

一直都寻找在Python下方便控制子进程运行时间的脚本。虽然网上有很多的好方法,但是都不能满足我的需求(也是我资质太低看别人的脚本总感觉太吃力,总有些看不明白的地方)。

下面这个脚本和网上一样利用了subprocess函数创建一个子进程控制脚本。(闲话少说,直接上菜!!!)

#!/usr/bin/pythonimport subprocess,timedef Test_ilo():    ilo_ip = '10.212.236.12'    sn_nu = 'BDSGJ11275067'    Returncode = "over"    cmd = 'sh ilo_test.sh %s %s' %(ilo_ip,sn_nu)    child = subprocess.Popen(cmd,stdout = subprocess.PIPE,shell = True)    timeout = 10    child_pid = child.pid    while True:        while_begin = time.time()        Flag = child.poll()        print Flag        if  Flag == 0 and timeout > 0:            Returncode = child.stdout.read()            print Returncode            break        elif not Flag and timeout < 0:            child.kill()            print Returncode            break        else:            time.sleep(1)if __name__ == '__main__':  print "Test_ilo", Test_ilo()


这里有个最致命的地方就是Flag的判断绝对不能写成Flag is ‘None’(兄弟我吃了不少亏啊)。
其中使用的一些函数就靠大家自己去找了,小弟也就不班门弄斧了。


0 0