下面是运行返回其stdout数据的任意命令的Python代码,或者对非零退出代码引发异常:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)communicate用于等待进程退出:
stdoutdata, stderrdata = proc.communicate()subprocess模块不支持超时--停止运行超过X秒的进程的能力--因此,communicate可能要花费很长时间才能运行。
在程序中实现超时的最简单的方法是什么?
发布于 2016-08-23 19:04:00
该解决方案在发生shell=True的情况下杀死进程树,将参数传递给进程(或不传递),具有超时,并获取回调的stdout、stderr和进程输出(kill_proc_tree使用psutil )。这是基于几个解决方案张贴在其中,包括jcollado的。张贴回应的评论,由Anson和jradice在jcollado的答复。在Windows 2012和Ubuntu 14.04中进行了测试。请注意,对于Ubuntu,您需要更改parent.children(.)呼叫parent.get_children(.)。
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
children = parent.children(recursive=True)
for child in children:
child.kill()
psutil.wait_procs(children, timeout=5)
if including_parent:
parent.kill()
parent.wait(5)
def run_with_timeout(cmd, current_dir, cmd_parms, timeout):
def target():
process = subprocess.Popen(cmd, cwd=current_dir, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the process to terminate
if (cmd_parms == ""):
out, err = process.communicate()
else:
out, err = process.communicate(cmd_parms)
errcode = process.returncode
thread = Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
me = os.getpid()
kill_proc_tree(me, including_parent=False)
thread.join()https://stackoverflow.com/questions/1191374
复制相似问题