Kill a function while it's being executed

Noam Aigerman noama at answers.com
Tue Feb 17 13:53:40 EST 2009


Hi,
Sorry for resurrecting an old thread, but it just bothers me that this
is the best way that python has to deal with killing running
functions... it's quite an ugly hack, no?

Is it a feature that's needed bit missing from python, or is it left out
on purpose (same way like java has deprecated thread.stop and
thread.suspend because they were not safe)?

Thanks, Noam

 

-----Original Message-----
From: python-list-bounces+noama=answers.com at python.org
[mailto:python-list-bounces+noama=answers.com at python.org] On Behalf Of
Albert Hopkins
Sent: Wednesday, February 04, 2009 5:26 PM
To: python-list at python.org
Subject: Re: Kill a function while it's being executed

On Wed, 2009-02-04 at 13:40 +0200, Noam Aigerman wrote:
> Hi All,
> I have a script in which I receive a list of functions. I iterate over
> the list and run each function. This functions are created by some
other
> user who is using the lib I wrote. Now, there are some cases in which
> the function I receive will never finish (stuck in infinite loop).
> Suppose I use a thread which times the amount of time passed since the
> function has started, Is there some way I can kill the function after
a
> certain amount of time has passed (without asking the user who's
giving
> me the list of functions to make them all have some way of notifying
> them to finish)?
> Thanks, Noam

Noam, did you hijack a thread?

You could decorate the functions with a timeout function.  Here's one
that I either wrote or copied from a recipe (can't recall):

class FunctionTimeOut(Exception):
    pass

def function_timeout(seconds):
    """Function decorator to raise a timeout on a function call"""
    import signal

    def decorate(f):
        def timeout(signum, frame):
            raise FunctionTimeOut()

        def funct(*args, **kwargs):
            old = signal.signal(signal.SIGALRM, timeout)
            signal.alarm(seconds)

            try:
                result = f(*args, **kwargs)
            finally:
                signal.signal(signal.SIGALRM, old)
            signal.alarm(0)
            return result

        return funct

    return decorate


Then

func_dec = function_timeout(TIMEOUT_SECS)
for func in function_list:
    timeout_function = func_dec(func)
    try:
        timeout_function(...)
    except FunctionTimeout:
        ...


-a



--
http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list