我想获取我的子流程的输出。由于它无限期运行,我想在满足某些条件时终止它。
当我使用启动子check_output
进程时,我得到了输出,但是没有终止进程的句柄:
output = subprocess.check_output(cmd, shell=True)
当我使用Popen
或启动子流程时run
,我得到一个终止流程的句柄,但没有输出。
p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
我怎样才能两者兼得?
什么时候可以知道您已经获得了完整的过程输出?当进程终止时。因此,无需手动终止它。只需等待它结束,然后使用即可check_output
。
现在,如果您要等待给定模式出现,然后终止,这就是其他内容。只需逐行读取,如果某些模式匹配,则中断循环并结束该过程
p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # add stderr=subprocess.PIPE) to merge output & error
for line in p.stdout:
if b"some string" in line: # output is binary
break
p.kill() # or p.terminate()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句