with timeout(...):

Klaas mike.klaas at gmail.com
Mon Mar 26 21:20:44 EDT 2007


On Mar 26, 3:30 am, Nick Craig-Wood <n... at craig-wood.com> wrote:
> Did anyone write a contextmanager implementing a timeout for
> python2.5?
>
> I'd love to be able to write something like
>
>     with timeout(5.0) as exceeded:
>         some_long_running_stuff()
>     if exceeded:
>         print "Oops - took too long!"
>
> And have it work reliably and in a cross platform way!

Doubt it.  But you could try:

class TimeoutException(BaseException):
   pass

class timeout(object):
   def __init__(self, limit_t):
       self.limit_t = limit
       self.timer = None
       self.timed_out = False
   def __nonzero__(self):
       return self.timed_out
   def __enter__(self):
       self.timer = threading.Timer(self.limit_t, ...)
       self.timer.start()
       return self
   def __exit__(self, exc_c, exc, tb):
       if exc_c is TimeoutException:
          self.timed_out = True
          return True # suppress exception
       return False # raise exception (maybe)

where '...' is a ctypes call to raise the given exception in the
current thread (the capi call PyThreadState_SetAsyncExc)

Definitely not fool-proof, as it relies on thread switching.  Also,
lock acquisition can't be interrupted, anyway.  Also, this style of
programming is rather unsafe.

But I bet it would work frequently.

-Mike




More information about the Python-list mailing list