运行一个进程,如果它在一小时内没有结束就杀死它 [英] Run a process and kill it if it doesn't end within one hour

查看:23
本文介绍了运行一个进程,如果它在一小时内没有结束就杀死它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Python 中执行以下操作.我想生成一个进程(子进程模块?),并且:

I need to do the following in Python. I want to spawn a process (subprocess module?), and:

  • 如果进程正常结束,从它终止的那一刻开始继续;
  • 如果,否则,进程卡住"并且在(比如)一小时内没有终止,杀死它并继续(可能再试一次,在一个循环中).

实现此目的最优雅的方法是什么?

What is the most elegant way to accomplish this?

推荐答案

subprocess 模块将成为您的朋友.启动该过程以获取 Popen 对象,然后将其传递给这样的函数.请注意,这只会在超时时引发异常.如果需要,您可以捕获异常并调用 Popen 进程上的 kill() 方法.(kill 是 Python 2.6 中的新功能,顺便说一句)

The subprocess module will be your friend. Start the process to get a Popen object, then pass it to a function like this. Note that this only raises exception on timeout. If desired you can catch the exception and call the kill() method on the Popen process. (kill is new in Python 2.6, btw)

import time

def wait_timeout(proc, seconds):
    """Wait for a process to finish, or raise exception after timeout"""
    start = time.time()
    end = start + seconds
    interval = min(seconds / 1000.0, .25)

    while True:
        result = proc.poll()
        if result is not None:
            return result
        if time.time() >= end:
            raise RuntimeError("Process timed out")
        time.sleep(interval)

这篇关于运行一个进程,如果它在一小时内没有结束就杀死它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆