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

http://guozhiwei.iteye.com/blog/973793

一:循环 忙等 子进程结束

 1 import subprocess  
 2 import os  
 3 import time  
 4 tt = '555'  
 5 cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt  
 6 print time.time()  
 7 sub2 = subprocess.Popen(cmd, shell=True)  
 8 while 1:  
 9     ret1 = subprocess.Popen.poll(sub2)  
10     if ret1 == 0:  
11         print sub2.pid,'end'  
12         break  
13     elif ret1 is None:  
14         print  'running'  
15         time.sleep(1)  
16     else:  
17         print sub2.pid,'term'  
18         break  
19 print time.time()  

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

 1 import subprocess  
 2 import select  
 3 import time  
 4 import signal  
 5 import os  
 6   
 7 tt = '555'  
 8 cmd = "python /home/100003/python/mypython/sub2.py "+" 333"+" 444 "+tt  
 9 timeout = 3  
10 pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell = True)  
11 print time.time()  
12 while 1:  
13     while_begin = time.time()  
14     print 'timeout',timeout  
15     fs = select.select([pro.stdout], [], [], timeout)  
16     if pro.stdout in fs[0]:  
17         tmp = pro.stdout.read()  
18         print 'read', tmp  
19         if not tmp:  
20             print 'end'  
21             print time.time()  
22             break  
23     else:  
24         print 'outoftime'  
25         print os.kill(pro.pid, signal.SIGKILL),  
26         break  
27     timeout = timeout - (time.time() - while_begin)

 

posted @ 2013-05-03 16:43  vivianC  阅读(1600)  评论(0编辑  收藏  举报