another try: "timout actions"

Klaus Neuner klaus_neuner82 at yahoo.de
Fri Oct 29 15:30:04 CEST 2004


Hello,

as I am desperately searching for a (straightforward) solution of the
following problem, I'll give it another try:

How can I tell Python to do things of the following kind:

for n seconds try to do:
    somefunc()
other_func()

somefunc() should be allowed to imply ANY activity Python is
capable to do. When the n seconds are over, Python should not exit the
program but execute other_func().

It turned out that the module signal is a solution for some but not
for all instances of somefunc(): If somefunc() contains a regexp match
that does not terminate (in a reasonable time), then the program will
not go on to other_func() (after n seconds). You can verify this by
running the programs (1) and (2) given below.

So, what other ways are there to code actions of the type described
above? Which way would be the cleanest and most straightforward? (I
don't want to use a program call, because this would decrease
readability, portability and other good properties a lot.)

Thanks in advance and sorry for asking the same question twice.

Klaus


#############################################################

# (1)

import sys, signal


class Timeout(Exception): 
    pass

def alarm_handler(signum, frame):
    raise Timeout

try:
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(3) 
    n = 0
    while 1:
        print n
        n = n+1
except Timeout:
    print "Time over."

#############################################################

# (2)

import sys, signal, re

class Timeout(Exception): 
    pass

def alarm_handler(signum, frame):
    raise Timeout

try:
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(3) 
    re.search("a(((.)*c)*d)*e", "abcdf"*20)
except Timeout:
    print "Time over."



More information about the Python-list mailing list