Python subprocess执行持续输出shell命令的控制


研究了大半天,为了获取持续输出的shell指令结果,并对结果进行分析,一直因为无法控制subprocess开启的子进程头疼,研究了半天,参考众多大神的博客后,终于实现,目前已时间为控制点,在实际业务中,可以通过判断业务执行是否完成来达到停止subprocess子进程的目的。

 1 #程序执行终止时间为当前时刻延迟15秒
 2 stoptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+10))
 3 def run_adbshell():
 4     p = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
 5     while True:
 6         line=p.stdout.readline().strip()
 7         print(line)
 8         #当前时间
 9         curtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
10         if curtime>=stoptime:
11             #终止子进程
12             p.terminate()
13             #等待子进程终止后跳出while循环
14             if subprocess.Popen.poll(p) is not None:
15                 break
16             else:
17                 print(u'等待subprocess子进程终止。')
18     print(u'完成')

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM