您的位置:首页 > 编程语言 > Python开发

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

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

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

#!/usr/bin/python
import subprocess,time
def 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’(兄弟我吃了不少亏啊)。

其中使用的一些函数就靠大家自己去找了,小弟也就不班门弄斧了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: