您的位置:首页 > 运维架构 > Shell

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

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

#程序执行终止时间为当前时刻延迟15秒
stoptime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()+10))
def run_adbshell():
p = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
while True:
line=p.stdout.readline().strip()
print(line)
#当前时间
curtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
if curtime>=stoptime:
#终止子进程
p.terminate()
#等待子进程终止后跳出while循环
if subprocess.Popen.poll(p) is not None:
break
else:
print(u'等待subprocess子进程终止。')
print(u'完成')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: