Package coro :: Module optional
[hide private]
[frames] | no frames]

Source Code for Module coro.optional

 1  # Copyright (c) 2002-2011 IronPort Systems and Cisco Systems 
 2  #  
 3  # Permission is hereby granted, free of charge, to any person obtaining a copy 
 4  # of this software and associated documentation files (the "Software"), to deal 
 5  # in the Software without restriction, including without limitation the rights 
 6  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 7  # copies of the Software, and to permit persons to whom the Software is 
 8  # furnished to do so, subject to the following conditions: 
 9  #  
10  # The above copyright notice and this permission notice shall be included in 
11  # all copies or substantial portions of the Software. 
12  #  
13  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
14  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
15  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
16  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
17  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
18  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
19  # SOFTWARE. 
20   
21  # $Header: //prod/main/ap/shrapnel/coro/optional.py#3 $ 
22   
23  """Functions that can run in or out of coro. 
24   
25  This module provides emulation for some functions to run whether or not the 
26  coro event loop is running. 
27  """ 
28   
29  __version__ = '$Revision: #3 $' 
30   
31  import coro 
32  import signal 
33  import time 
34   
35 -class _shutdown_sigalrm_exc (Exception):
36 pass
37
38 -def _shutdown_sigalrm_handler(unused_signum, unused_frame):
39 raise _shutdown_sigalrm_exc
40
41 -def with_timeout(timeout, function, *args, **kwargs):
42 """Call a function with a timeout. 43 44 This version supports running even if the coro event loop isn't running by 45 using SIGALRM. 46 47 See `coro._coro.sched.with_timeout` for more detail. 48 49 :Parameters: 50 - `timeout`: The number of seconds to wait before raising the timeout. 51 May be a floating point number. 52 - `function`: The function to call. 53 54 :Return: 55 Returns the return value of the function. 56 57 :Exceptions: 58 - `coro.TimeoutError`: The timeout expired. 59 """ 60 if coro.coro_is_running(): 61 return coro.with_timeout(timeout, function, *args, **kwargs) 62 else: 63 # Use sigalarm to do the magic. 64 old_sigalrm_handler = signal.signal(signal.SIGALRM, _shutdown_sigalrm_handler) 65 try: 66 try: 67 signal.alarm(timeout) 68 return function(*args, **kwargs) 69 except _shutdown_sigalrm_exc: 70 raise coro.TimeoutError 71 finally: 72 signal.alarm(0) 73 signal.signal(signal.SIGALRM, old_sigalrm_handler)
74
75 -def sleep_relative(delta):
76 """Sleep for a period of time. 77 78 :Parameters: 79 - `delta`: The number of seconds to sleep. 80 """ 81 time.sleep(delta)
82