Timing out arbitrary functions

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Dec 24 07:36:58 EST 2005


I have a problem and I don't know where to start looking for a solution.

I have a class that needs to call an arbitrary function and wait for a
result. The function, being completely arbitrary and not under my control,
may be very time consuming and possibly may not even halt. My class needs
to be able to give up waiting for a result after a specified amount of
time.

I'm thinking something conceptually like this:

# pseudo-code:
set time out to 30 seconds
try:
    result = somefunction()
except TimeOut:
    # 30 second time out happened
    print "somefunction() timed out without returning"
else:
    print "somefunction() returned %s" % result


The easy (for some definition of easy) solution would be to code
somefunction() so that it raised an exception if it hadn't returned a
result within a certain time. Unfortunately, I can't do rely on that -- I
only have control over the calling code, not the called somefunction(),
which may be any arbitrary function.

How do others handle something like this? What should I be looking for?
I'm after a lightweight solution, if any such thing exists.

Thanks,


-- 
Steven.




More information about the Python-list mailing list