how to run an arbitrary function with timeout?

Mark Day mday at apple.com
Fri May 14 19:13:36 EDT 2004


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.

-Mark



More information about the Python-list mailing list