def with_timeout(timeout, function, *args, **kwargs): """Call a function with a timeout. This version supports running even if the coro event loop isn't running by using SIGALRM. See `coro._coro.sched.with_timeout` for more detail. :Parameters: - `timeout`: The number of seconds to wait before raising the timeout. May be a floating point number. - `function`: The function to call. :Return: Returns the return value of the function. :Exceptions: - `coro.TimeoutError`: The timeout expired. """ if coro.coro_is_running(): return coro.with_timeout(timeout, function, *args, **kwargs) else: # Use sigalarm to do the magic. old_sigalrm_handler = signal.signal(signal.SIGALRM, _shutdown_sigalrm_handler) try: try: signal.alarm(timeout) return function(*args, **kwargs) except _shutdown_sigalrm_exc: raise coro.TimeoutError finally: signal.alarm(0) signal.signal(signal.SIGALRM, old_sigalrm_handler)
def sleep(x): """Sleep that works in both coro and non-coro environments.""" if GOT_CORO and coro.coro_is_running(): coro.sleep_relative(x) else: time.sleep(x)
def P(x): """Uses coro.print_stderr in a coro environment, else plain print.""" if GOT_CORO and coro.coro_is_running(): coro.print_stderr("%s\n" % x) else: print x
def make_socket(self, *args, **kwargs): """Make socket in both coro and non-coro environments. Returns socket, send function; the latter accounts for different behavior between socket.send and coro_socket.send by using self.sendall instead.""" if GOT_CORO and coro.coro_is_running(): sock = coro.make_socket(*args, **kwargs) sender = sock.send else: sock = socket.socket(*args, **kwargs) sender = self.sendall return (sock, sender)