how to run an arbitrary function with timeout?
Joseph T. Bore
jbore at tjtech.com
Mon May 17 09:33:59 EDT 2004
Mark Day <mday at apple.com> writes:
> In article <2004051413541084557280 at k2.sage.att.com>, Garry Hodgson
> <garry at sage.att.com> wrote:
>
>> i would like a function RunWithTimeout( func, args, timeout )
>> i would like it to invoke the function func on arguments args.
>> if timeout seconds elapse before func(args) returns, i would
>> like it to raise an exception. if func(args) returns before timeout
>> seconds, i would like it return the result.
>
> I'm guessing you want the exception raised after func has executed for
> timeout seconds (as opposed to waiting for func to complete).
>
> Since you can't stop func from the outside (as Tim said), I suppose you
> could run func in a separate thread. From the original thread, you'd
> have to wait for either timeout seconds or until func completes,
> whichever comes first. If the timeout happened first, then raise the
> exception (else you presumably return func's result). I'm no expert on
> threading in Python, but I'll bet the Library Reference has the
> information you need.
just use alarm and use a signal handler to be called after N seconds,
this is how I do it: (I've omitted the definition of the exception for
brevity)
-----------------------------------------------------------
import signal
#
# a alarm signal handler
#
def alarmHandler(signum, frame):
raise TimeExceededError, "Your command ran too long"
#
# a function that would run for too long
#
def infinite():
while 1:
pass
return
#
# set the alarm signal handler, and set the alarm to 1 second
#
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(1)
#
# the function infinite would never return, after 1 second the signalHandler
# is called, which immediately just raises the exception.
#
try:
infinite()
except TimeExceededError:
# but after 1 second, the alarmHandler raises this
# exception
print "code must have gone crazy..."
-----------------------------------------------------------
More information about the Python-list
mailing list