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

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

问题描述

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

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

  • 如果该流程正常结束,则从该流程终止之时起继续准确地运行;
  • 否则,该进程陷入困境"并且没有在(例如)一个小时内终止,以终止该进程并继续(可能在一个循环中再次尝试).

最优雅的方法是什么?

推荐答案

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

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天全站免登陆