当前位置: 首页>>代码示例>>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;未经允许,请勿转载。