1 # Copyright (c) 2009-2010 Denis Bilenko, denis.bilenko at gmail com
2 # Copyright (c) 2010 Eventlet Contributors (see AUTHORS)
3 # and licensed under the MIT license:
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.from eventlet.support import greenlets as greenlet
23 from eventlet.support import greenlets as greenlet
24 from eventlet.hubs import get_hub
31 # deriving from BaseException so that "except Exception as e" doesn't catch
35 class Timeout(BaseException):
36 """Raises *exception* in the current greenthread after *timeout* seconds.
38 When *exception* is omitted or ``None``, the :class:`Timeout` instance
39 itself is raised. If *seconds* is None, the timer is not scheduled, and is
40 only useful if you're planning to raise it directly.
42 Timeout objects are context managers, and so can be used in with statements.
43 When used in a with statement, if *exception* is ``False``, the timeout is
44 still raised, but the context manager suppresses it, so the code outside the
45 with-block won't see it.
48 def __init__(self, seconds=None, exception=None):
49 self.seconds = seconds
50 self.exception = exception
55 """Schedule the timeout. This is called on construction, so
56 it should not be called explicitly, unless the timer has been
58 assert not self.pending, \
59 '%r is already started; to restart it, cancel it first' % self
60 if self.seconds is None: # "fake" timeout (never expires)
62 elif self.exception is None or isinstance(self.exception, bool): # timeout that raises self
63 self.timer = get_hub().schedule_call_global(
64 self.seconds, greenlet.getcurrent().throw, self)
65 else: # regular timeout with user-provided exception
66 self.timer = get_hub().schedule_call_global(
67 self.seconds, greenlet.getcurrent().throw, self.exception)
72 """True if the timeout is scheduled to be raised."""
73 if self.timer is not None:
74 return self.timer.pending
79 """If the timeout is pending, cancel it. If not using
80 Timeouts in ``with`` statements, always call cancel() in a
81 ``finally`` after the block of code that is getting timed out.
82 If not canceled, the timeout will be raised later on, in some
83 unexpected section of the application."""
84 if self.timer is not None:
89 classname = self.__class__.__name__
94 if self.exception is None:
97 exception = ' exception=%r' % self.exception
98 return '<%s at %s seconds=%s%s%s>' % (
99 classname, hex(id(self)), self.seconds, exception, pending)
103 >>> raise Timeout # doctest: +IGNORE_EXCEPTION_DETAIL
104 Traceback (most recent call last):
108 if self.seconds is None:
110 if self.seconds == 1:
114 if self.exception is None or self.exception is True:
115 return '%s second%s' % (self.seconds, suffix)
116 elif self.exception is False:
117 return '%s second%s (silent)' % (self.seconds, suffix)
119 return '%s second%s (%s)' % (self.seconds, suffix, self.exception)
122 if self.timer is None:
126 def __exit__(self, typ, value, tb):
128 if value is self and self.exception is False:
132 def with_timeout(seconds, function, *args, **kwds):
133 """Wrap a call to some (yielding) function with a timeout; if the called
134 function fails to return before the timeout, cancel it and return a flag
137 timeout_value = kwds.pop("timeout_value", _NONE)
138 timeout = Timeout(seconds)
141 return function(*args, **kwds)
142 except Timeout as ex:
143 if ex is timeout and timeout_value is not _NONE: