How to timeout a python method that may infinite loop

I have a method that may or may not infinite loop depending on user input.  I would like to wrap the call to it in some way so that I may specify a time out and, in the case that it runs longer than that time out, return None.

I copied the code below from forums, but it does not seem to work.  (I get the error that "signal" does not contain a member "SIGALRM").  I think it might not work on windows based on what I've read on some other forums.  

I've also seen some solutions using win32process.CreateProcess.  But this seems to be used to run outside windows program; not just a python method (whose return value I need).

Does anyone know what would work?

Thanks,
Matthew


import signal, time

class TimedOutExc(Exception):
    def __init__(self, value = "Timed Out"):
        self.value = value
    def __str__(self):
        return repr(self.value)

def TimedOutFn(f, timeout, *args, **kwargs):
    def handler(signum, frame):
        raise TimedOutExc()
   
    old = signal.signal(signal.SIGALRM, handler)
    signal.alarm(timeout)
    try:
        result = f(*args, **kwargs)
    finally:
        signal.signal(signal.SIGALRM, old)
    signal.alarm(0)
    return result


def timed_out(timeout):
    def decorate(f):
        def handler(signum, frame):
            raise TimedOutExc()
       
        def new_f(*args, **kwargs):
            old = signal.signal(signal.SIGALRM, handler)
            signal.alarm(timeout)
            try:
                result = f(*args, **kwargs)
            finally:
                signal.signal(signal.SIGALRM, old)
            signal.alarm(0)
            return result
       
        new_f.func_name = f.func_name
        return new_f

    return decorate


def fn_1(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(4)
def fn_2(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_3(secs):
    time.sleep(secs)
    return "Finished"

@timed_out(2)
def fn_4(secs):
    try:
        time.sleep(secs)
        return "Finished"
    except TimedOutExc:
        print "(Caught TimedOutExc, so cleaining up, and re-raising it) - ",
        raise TimedOutExc
       
if __name__ == '__main__':

    try:
        print "fn_1 (sleep 2, timeout 4): ",
        print TimedOutFn(fn_1, 4, 2)
    except TimedOutExc:
        print "took too long"
       
    try:
        print "fn_2 (sleep 2, timeout 4): ",
        print fn_2(2)
    except TimedOutExc:
        print "took too long"

    try:
        print "fn_1 (sleep 4, timeout 2): ",
        print TimedOutFn(fn_1, 2, 4)
    except TimedOutExc:
        print "took too long"
       
    try:
        print "fn_3 (sleep 4, timeout 2): ",
        print fn_3(4)
    except TimedOutExc:
        print "took too long"

    try:
        print "fn_4 (sleep 4, timeout 2): ",
        print fn_4(4)
    except TimedOutExc:
        print "took too long"
matttschAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
Try to use threading. See the simpler http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473878 and the improved http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752. The problem is with terminating the thread that waits for the input.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
matttschAuthor Commented:
Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.