Run a process and kill it if it doesn't end within one hour

Federico A. Ramponi picture Federico A. Ramponi · Aug 31, 2009 · Viewed 29.9k times · Source

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

  • if the process ends normally, to continue exactly from the moment it terminates;
  • if, otherwise, the process "gets stuck" and doesn't terminate within (say) one hour, to kill it and continue (possibly giving it another try, in a loop).

What is the most elegant way to accomplish this?

Answer

Peter Shinners picture Peter Shinners · Aug 31, 2009

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)