Timer interrupt of execution?

Mark Hobbes2176 at yahoo.com
Tue Oct 28 11:08:01 EST 2003


Hello all,

I know why the following doesn't work ... I can't figure out how to make it
work like I want it to.  Basically, I only want the loop computing
fibonacci numbers to run for approx 5 seconds.  The timer fires, the
exception is raised, but it is not caught ... because the execution stack
for the function that raises isn't in the same thread as the try: except:.

How do you fix this?  Is it better to do this without exceptions as the
control construct?

Regards,
Mark

PS I tried two positions of starting the thread ... unfortunately, lexical
scope doesn't affect the execution stack ... it's still in its own space, I
guess.

#!/usr/bin/env python

import threading


class TimeException(Exception):
    def __init__(self, i):
        self.msg = "Out of time"

def raiser():
    print "raising"
    raise TimeException
    print "raised"

def fib(x):
    if x == 0 or x == 1:
        return 1
    else:
        return fib(x-1) + fib(x-2)

#position 1
#t = threading.Timer(5.0, raiser)
#t.start()

try:
    # position 2
    t = threading.Timer(5.0, raiser)
    t.start()
    for i in range(1,10000000):
        t = fib(i)
        print i, ": ", t
except TimeException:
    print "thread done"
except:
    print "other exception"





More information about the Python-list mailing list