python subprocess模块 监控子进程的2种方式 忙等待和立即返回同时设置子进程超时...

下面的资料是关于python subprocess模块 监控子进程的2种方式 忙等待和立即返回同时设置子进程超时时间的代码。

import subprocess  
import os  
import time  
tt = '555'  
cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt  
print time.time()  
sub2 = subprocess.Popen(cmd, shell=True)  
while 1:  
    ret1 = subprocess.Popen.poll(sub2)  
    if ret1 == 0:  
        print sub2.pid,'end'  
        break  
    elif ret1 is None:  
        print  'running'  
        time.sleep(1)  
    else:  
        print sub2.pid,'term'  
        break  
print time.time()  

二:子进程结束立即返回使用select模块同时可设置子进程的超时时间

import subprocess  
import select  
import time  
import signal  
import os  

tt = '555'  
cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt  
timeout = 3  
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell = True)  
print time.time()  
while 1:  
    while_begin = time.time()  
    print 'timeout',timeout  
    fs = select.select([pro.stdout], [], [], timeout)  
    if pro.stdout in fs[0]:  
        tmp = pro.stdout.read()  
        print 'read', tmp  
        if not tmp:  
            print 'end'  
            print time.time()  
            break  
    else:  
        print 'outoftime'  
        print os.kill(pro.pid, signal.SIGKILL),  
        break  
    timeout = timeout - (time.time() - while_begin)  

转载于:https://blog.51cto.com/14129678/2347839

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值