當前位置: 首頁>>代碼示例>>Python>>正文


Python signal.alarm方法代碼示例

本文整理匯總了Python中signal.alarm方法的典型用法代碼示例。如果您正苦於以下問題:Python signal.alarm方法的具體用法?Python signal.alarm怎麽用?Python signal.alarm使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在signal的用法示例。


在下文中一共展示了signal.alarm方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_multiprocessing

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def test_multiprocessing(app):
    """Tests that the number of children we produce is correct"""
    # Selects a number at random so we can spot check
    num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
    process_list = set()

    def stop_on_alarm(*args):
        for process in multiprocessing.active_children():
            process_list.add(process.pid)
            process.terminate()

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(3)
    app.run(HOST, PORT, workers=num_workers)

    assert len(process_list) == num_workers 
開發者ID:huge-success,項目名稱:sanic,代碼行數:18,代碼來源:test_multiprocessing.py

示例2: test_multiprocessing_with_blueprint

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def test_multiprocessing_with_blueprint(app):
    # Selects a number at random so we can spot check
    num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
    process_list = set()

    def stop_on_alarm(*args):
        for process in multiprocessing.active_children():
            process_list.add(process.pid)
            process.terminate()

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(3)

    bp = Blueprint("test_text")
    app.blueprint(bp)
    app.run(HOST, PORT, workers=num_workers)

    assert len(process_list) == num_workers


# this function must be outside a test function so that it can be
# able to be pickled (local functions cannot be pickled). 
開發者ID:huge-success,項目名稱:sanic,代碼行數:24,代碼來源:test_multiprocessing.py

示例3: run

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def run(self, address, timeout_seconds):
        self.jitter.init_run(address)

        try:
            signal.alarm(timeout_seconds)
            self.jitter.continue_run()
        except (AssertionError, RuntimeError, ValueError,
                KeyError, IndexError, TimeoutException) as _:
            return False
        except Exception as error:
            self.logger.exception(error)
            return False
        finally:
            signal.alarm(0)

        return True 
開發者ID:cea-sec,項目名稱:Sibyl,代碼行數:18,代碼來源:miasm.py

示例4: __init__

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def __init__(cls, name, bases, attrs):
            super(RMParserType, cls).__init__(name, bases, attrs)
            if not hasattr(cls, "parsers"):
                cls.parsers = []
            else:
                cls.registerParser(cls)

            # Add timeout to perform function
            if hasattr(cls, "perform"):
                def timedPerform(self):
                    global USE_THREADING__
                    if not USE_THREADING__:
                        seconds = 10 * 60
                        _old_handler = signal.signal(signal.SIGALRM, _handle_timeout)
                        signal.alarm(seconds)
                    try:
                        result = attrs["perform"](self)
                    except RMTimeoutError, e:
                        log.error("*** Timeout occurred while running parser %s" % self.parserName)
                        log.exception(e)
                        return None
                    finally: 
開發者ID:sprinkler,項目名稱:rainmachine-developer-resources,代碼行數:24,代碼來源:rmParser.py

示例5: timeout

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator 
開發者ID:KanoComputing,項目名稱:kano-toolset,代碼行數:19,代碼來源:timeout.py

示例6: timeout

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def timeout(timeout_time, default):
        '''
        Decorate a method so it is required to execute in a given time period,
        or return a default value.
        '''
        def timeout_function(f):
            def f2(*args):
                def timeout_handler(signum, frame):
                    raise MethodTimer.DecoratorTimeout()

                old_handler = signal.signal(signal.SIGALRM, timeout_handler)
                # triger alarm in timeout_time seconds
                signal.alarm(timeout_time)
                try:
                    retval = f(*args)
                except MethodTimer.DecoratorTimeout:
                    return default
                finally:
                    signal.signal(signal.SIGALRM, old_handler)
                signal.alarm(0)
                return retval
            return f2
        return timeout_function 
開發者ID:istresearch,項目名稱:scrapy-cluster,代碼行數:25,代碼來源:method_timer.py

示例7: timeout

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def timeout(seconds=0, minutes=0, hours=0):
    """Add a signal-based timeout to any block of code.
    If multiple time units are specified, they will be added together to determine time limit.
    Usage:
    with timeout(seconds=5):
        my_slow_function(...)
    Args:
        - seconds: The time limit, in seconds.
        - minutes: The time limit, in minutes.
        - hours: The time limit, in hours.
    """

    limit = seconds + 60 * minutes + 3600 * hours

    def handler(signum, frame):
        raise TimeoutError('timed out after {} seconds'.format(limit))

    try:
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(limit)

        yield
    finally:
        signal.alarm(0) 
開發者ID:aws,項目名稱:sagemaker-pytorch-training-toolkit,代碼行數:26,代碼來源:timeout.py

示例8: timeout

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def timeout(seconds=0, minutes=0, hours=0):
    """
    Add a signal-based timeout to any block of code.
    If multiple time units are specified, they will be added together to determine time limit.
    Usage:
    with timeout(seconds=5):
        my_slow_function(...)
    Args:
        - seconds: The time limit, in seconds.
        - minutes: The time limit, in minutes.
        - hours: The time limit, in hours.
    """

    limit = seconds + 60 * minutes + 3600 * hours

    def handler(signum, frame):
        raise TimeoutError('timed out after {} seconds'.format(limit))

    try:
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(limit)

        yield
    finally:
        signal.alarm(0) 
開發者ID:aws,項目名稱:sagemaker-mxnet-inference-toolkit,代碼行數:27,代碼來源:timeout.py

示例9: test_wakeup_fd_early

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def test_wakeup_fd_early(self):
        import select

        signal.alarm(1)
        try:
            before_time = time.time()
            # We attempt to get a signal during the sleep,
            # before select is called
            time.sleep(self.TIMEOUT_FULL)
            mid_time = time.time()
        finally:
            signal.alarm(0)

        self.assertTrue(mid_time - before_time < self.TIMEOUT_HALF)
        select.select([self.read], [], [], self.TIMEOUT_FULL)
        after_time = time.time()
        self.assertTrue(after_time - mid_time < self.TIMEOUT_HALF) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_signal.py

示例10: check_interrupted_read_retry

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
        """Check that a buffered read, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        def alarm_handler(sig, frame):
            os.write(w, b"bar")
        signal.signal(signal.SIGALRM, alarm_handler)
        try:
            rio = self.io.open(r, **fdopen_kwargs)
            os.write(w, b"foo")
            signal.alarm(1)
            # Expected behaviour:
            # - first raw read() returns partial b"foo"
            # - second raw read() returns EINTR
            # - third raw read() returns b"bar"
            self.assertEqual(decode(rio.read(6)), "foobar")
        finally:
            signal.alarm(0)
            rio.close()
            os.close(w)
            os.close(r) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:25,代碼來源:test_io.py

示例11: test_communicate_eintr

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def test_communicate_eintr(self):
        # Issue #12493: communicate() should handle EINTR
        def handler(signum, frame):
            pass
        old_handler = signal.signal(signal.SIGALRM, handler)
        self.addCleanup(signal.signal, signal.SIGALRM, old_handler)

        # the process is running for 2 seconds
        args = [sys.executable, "-c", 'import time; time.sleep(2)']
        for stream in ('stdout', 'stderr'):
            kw = {stream: subprocess.PIPE}
            with subprocess.Popen(args, **kw) as process:
                signal.alarm(1)
                try:
                    # communicate() will be interrupted by SIGALRM
                    process.communicate()
                finally:
                    signal.alarm(0) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_subprocess.py

示例12: run

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def run(self):
        """
        Run guest main thread
        """
        global virt
        global exiting
        virt = VirtioGuestPosix()
        slave = Thread(target=worker, args=(virt,))
        slave.start()
        signal.signal(signal.SIGUSR1, sigusr_handler)
        signal.signal(signal.SIGALRM, sigusr_handler)
        while not exiting:
            signal.alarm(1)
            signal.pause()
            catch = virt.catching_signal()
            if catch:
                signal.signal(signal.SIGIO, virt)
            elif catch is False:
                signal.signal(signal.SIGIO, signal.SIG_DFL)
            if catch is not None:
                virt.use_config.set()
        print("PASS: guest_exit")
        sys.exit(0) 
開發者ID:avocado-framework,項目名稱:avocado-vt,代碼行數:25,代碼來源:virtio_console_guest.py

示例13: check_interrupted_read_retry

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
        """Check that a buffered read, when it gets interrupted (either
        returning a partial result or EINTR), properly invokes the signal
        handler and retries if the latter returned successfully."""
        r, w = os.pipe()
        fdopen_kwargs["closefd"] = False
        def alarm_handler(sig, frame):
            os.write(w, b"bar")
        signal.signal(signal.SIGALRM, alarm_handler)
        try:
            rio = self.io.open(r, **fdopen_kwargs)
            os.write(w, b"foo")
            signal.alarm(1)
            # Expected behaviour:
            # - first raw read() returns partial b"foo"
            # - second raw read() returns EINTR
            # - third raw read() returns b"bar"
            self.assertEqual(decode(rio.read(6)), "foobar")
        finally:
            rio.close()
            os.close(w)
            os.close(r) 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:24,代碼來源:test_io.py

示例14: test_signals

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def test_signals(self):
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            signal.alarm(1)
            signal.pause()
            signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release() 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:25,代碼來源:test_threadsignals.py

示例15: start_stop_app

# 需要導入模塊: import signal [as 別名]
# 或者: from signal import alarm [as 別名]
def start_stop_app(random_name_app, **run_kwargs):
    def stop_on_alarm(signum, frame):
        raise KeyboardInterrupt("SIGINT for sanic to stop gracefully")

    signal.signal(signal.SIGALRM, stop_on_alarm)
    signal.alarm(1)
    try:
        random_name_app.run(HOST, PORT, **run_kwargs)
    except KeyboardInterrupt:
        pass 
開發者ID:huge-success,項目名稱:sanic,代碼行數:12,代碼來源:test_server_events.py


注:本文中的signal.alarm方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。