decorators and alarms

Jason Friedman jsf80238 at gmail.com
Fri May 22 22:15:54 EDT 2015


I have the following code to run a shell command and kill it if it
does not return within a certain amount of time:

def run_with_time_limit(command, limit):
    """Run the given command via a shell.
    Kill the command, and raise an exception, if the
    execution time exceeds <limit> seconds.
    Else return (exit_code, stdout, stderr, duration)."""
    class Alarm(Exception):
        pass
    def alarm_handler(signum, frame):
        raise Alarm
    start_stamp = time.time()
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(limit)
    try:
        process = subprocess.Popen(
            command,
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE,
            shell=True)
        stdout, stderr = process.communicate()
        duration = time.time() - start_stamp
        signal.alarm(0) # reset the alarm
    except Alarm:
        process.kill()
        raise Alarm("The command did not return within %(limit)s
seconds." % locals())
    return (process.returncode, stdout, stderr, duration)

run_with_time_limit("sleep 2", 1)

This works as desired.

But, I'd like to expand this to take some generic code, not just a
shell command, and terminate it if it does not return quickly.

@time_limiter
def generic_function(arg1, arg2, time_limit=10):
    do_some_stuff()
    do_some_other_stuff()
    return val1, val2

If generic_function does not finish within 10 seconds it would stop
executing and throw an exception.

May I have some hints, please?



More information about the Python-list mailing list