Python signal.signal() Examples

The following are 30 code examples of signal.signal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module signal , or try the search function .
Example #1
Source File: multiprocessor.py    From svviz with MIT License 11 votes vote down vote up
def __init__(self, name=""):
        self.barsToProgress = {}

        self.t0 = time.time()
        self.timeRemaining = "--"
        self.status = "+"
        self.name = name
        self.lastRedraw = time.time()
        self.isatty = sys.stdout.isatty()

        try:
            self.handleResize(None,None)
            signal.signal(signal.SIGWINCH, self.handleResize)
            self.signal_set = True
        except:
            self.term_width = 79 
Example #2
Source File: wio.py    From wio-cli with MIT License 7 votes vote down vote up
def cli(ctx):
    """\b
    Welcome to the Wio Command line utility!
    https://github.com/Seeed-Studio/wio-cli

    For more information Run: wio <command_name> --help
    """
    ctx.obj = Wio()
    cur_dir = os.path.abspath(os.path.expanduser("~/.wio"))
    if not os.path.exists(cur_dir):
        text = {"email":"", "token":""}
        os.mkdir(cur_dir)
        open("%s/config.json"%cur_dir,"w").write(json.dumps(text))
    db_file_path = '%s/config.json' % cur_dir
    config = json.load(open(db_file_path))
    ctx.obj.config = config

    signal.signal(signal.SIGINT, sigint_handler)

    if not verify:
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 
Example #3
Source File: util.py    From wechat-alfred-workflow with MIT License 7 votes vote down vote up
def __call__(self, *args, **kwargs):
        """Trap ``SIGTERM`` and call wrapped function."""
        self._caught_signal = None
        # Register handler for SIGTERM, then call `self.func`
        self.old_signal_handler = signal.getsignal(signal.SIGTERM)
        signal.signal(signal.SIGTERM, self.signal_handler)

        self.func(*args, **kwargs)

        # Restore old signal handler
        signal.signal(signal.SIGTERM, self.old_signal_handler)

        # Handle any signal caught during execution
        if self._caught_signal is not None:
            signum, frame = self._caught_signal
            if callable(self.old_signal_handler):
                self.old_signal_handler(signum, frame)
            elif self.old_signal_handler == signal.SIG_DFL:
                sys.exit(0) 
Example #4
Source File: test_break.py    From jawfish with MIT License 6 votes vote down vote up
def testTwoResults(self):
        unittest.installHandler()

        result = unittest.TestResult()
        unittest.registerResult(result)
        new_handler = signal.getsignal(signal.SIGINT)

        result2 = unittest.TestResult()
        unittest.registerResult(result2)
        self.assertEqual(signal.getsignal(signal.SIGINT), new_handler)

        result3 = unittest.TestResult()

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")

        self.assertTrue(result.shouldStop)
        self.assertTrue(result2.shouldStop)
        self.assertFalse(result3.shouldStop) 
Example #5
Source File: cmdline.py    From BASS with GNU General Public License v2.0 6 votes vote down vote up
def main(args, env):
    if len(args.samples) < 2:
        sys.stderr.write("Come on, give me at least two samples :(\n")
        return 1

    bass = Bass()
    job = Job()
    def received_sigterm(signal, frame):
        sys.stderr.write("Received SIGINT\n")
        bass.terminate()

    signal.signal(signal.SIGINT, received_sigterm)
    for path in args.samples:
        job.add_sample(path)
    bass.submit_job(job)
    while not job.status in (Job.STATUS_ERROR, Job.STATUS_FINISHED, Job.STATUS_CANCELED):
        time.sleep(1) 
Example #6
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unsubscribe(self):
        """Unsubscribe self.handlers from signals."""
        for signum, handler in self._previous_handlers.items():
            signame = self.signals[signum]

            if handler is None:
                self.bus.log('Restoring %s handler to SIG_DFL.' % signame)
                handler = _signal.SIG_DFL
            else:
                self.bus.log('Restoring %s handler %r.' % (signame, handler))

            try:
                our_handler = _signal.signal(signum, handler)
                if our_handler is None:
                    self.bus.log('Restored old %s handler %r, but our '
                                 'handler was not registered.' %
                                 (signame, handler), level=30)
            except ValueError:
                self.bus.log('Unable to restore %s handler %r.' %
                             (signame, handler), level=40, traceback=True) 
Example #7
Source File: concurrency.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def start_proc_mask_signal(proc):
    """
    Start process(es) with SIGINT ignored.

    Args:
        proc: (mp.Process or list)

    Note:
        The signal mask is only applied when called from main thread.
    """
    if not isinstance(proc, list):
        proc = [proc]

    with mask_sigint():
        for p in proc:
            if isinstance(p, mp.Process):
                if sys.version_info < (3, 4) or mp.get_start_method() == 'fork':
                    log_once("""
Starting a process with 'fork' method is efficient but not safe and may cause deadlock or crash.
Use 'forkserver' or 'spawn' method instead if you run into such issues.
See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods on how to set them.
""".replace("\n", ""),
'warn')  # noqa
            p.start() 
Example #8
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, freq = 100.0):
        EventDispatcher2.state_lock.acquire()
        if EventDispatcher2.ed_inum != 0:
            EventDispatcher2.state_lock.release()
            raise StdException('BZZZT, EventDispatcher2 has to be singleton!')
        EventDispatcher2.ed_inum = 1
        EventDispatcher2.state_lock.release()
        self.tcbs_lock = Lock()
        self.tlisteners = []
        self.slisteners = []
        self.signals_pending = []
        self.last_ts = MonoTime()
        self.my_ident = get_ident()
        self.elp = ElPeriodic(freq)
        self.elp.CFT_enable(signal.SIGURG)
        self.bands = [(freq, 0),] 
Example #9
Source File: compat.py    From sanic with MIT License 6 votes vote down vote up
def ctrlc_workaround_for_windows(app):
    async def stay_active(app):
        """Asyncio wakeups to allow receiving SIGINT in Python"""
        while not die:
            # If someone else stopped the app, just exit
            if app.is_stopping:
                return
            # Windows Python blocks signal handlers while the event loop is
            # waiting for I/O. Frequent wakeups keep interrupts flowing.
            await asyncio.sleep(0.1)
        # Can't be called from signal handler, so call it from here
        app.stop()

    def ctrlc_handler(sig, frame):
        nonlocal die
        if die:
            raise KeyboardInterrupt("Non-graceful Ctrl+C")
        die = True

    die = False
    signal.signal(signal.SIGINT, ctrlc_handler)
    app.add_task(stay_active) 
Example #10
Source File: signals.py    From jawfish with MIT License 6 votes vote down vote up
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler 
Example #11
Source File: concurrency.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def enable_death_signal(_warn=True):
    """
    Set the "death signal" of the current process, so that
    the current process will be cleaned with guarantee
    in case the parent dies accidentally.
    """
    if platform.system() != 'Linux':
        return
    try:
        import prctl    # pip install python-prctl
    except ImportError:
        if _warn:
            log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.',
                     'warn')
        return
    else:
        assert hasattr(prctl, 'set_pdeathsig'), \
            "prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'."
        # is SIGHUP a good choice?
        prctl.set_pdeathsig(signal.SIGHUP) 
Example #12
Source File: test_break.py    From jawfish with MIT License 6 votes vote down vote up
def testInterruptCaught(self):
        default_handler = signal.getsignal(signal.SIGINT)

        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")
        self.assertTrue(result.breakCaught) 
Example #13
Source File: test_break.py    From jawfish with MIT License 6 votes vote down vote up
def testSecondInterrupt(self):
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example #14
Source File: test_break.py    From jawfish with MIT License 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example #15
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def regSignal(self, signum, signal_cb, *cb_params, **cb_kw_args):
        sl = EventListener()
        if len([x for x in self.slisteners if x.signum == signum]) == 0:
            signal.signal(signum, self.signal)
        sl.signum = signum
        sl.cb_func = signal_cb
        sl.cb_params = cb_params
        sl.cb_kw_args = cb_kw_args
        self.slisteners.append(sl)
        return sl 
Example #16
Source File: Signal.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def cancel(self):
        signal(self.signum, self.previous_handler)
        self.callback = None
        self.parameters = None
        self.previous_handler = None 
Example #17
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def dispatchSignals(self):
        while len(self.signals_pending) > 0:
            signum = self.signals_pending.pop(0)
            for sl in [x for x in self.slisteners if x.signum == signum]:
                if sl not in self.slisteners:
                    continue
                try:
                    sl.cb_func(*sl.cb_params, **sl.cb_kw_args)
                except Exception as ex:
                    if isinstance(ex, SystemExit):
                        raise
                    dump_exception('EventDispatcher2: unhandled exception when processing signal event')
                if self.endloop:
                    return 
Example #18
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def unregSignal(self, sl):
        self.slisteners.remove(sl)
        if len([x for x in self.slisteners if x.signum == sl.signum]) == 0:
            signal.signal(sl.signum, signal.SIG_DFL)
        sl.cleanup() 
Example #19
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _handle_signal(self, signum=None, frame=None):
        """Python signal handler (self.set_handler subscribes it for you)."""
        signame = self.signals[signum]
        self.bus.log('Caught signal %s.' % signame)
        self.bus.publish(signame) 
Example #20
Source File: graceful_interrupt.py    From gated-graph-transformer-network with MIT License 5 votes vote down vote up
def __init__(self, sig=signal.SIGINT):
        self.sig = sig 
Example #21
Source File: Signal.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def log_signal(signum, sip_logger, signal_cb, cb_params):
    sip_logger.write('Dispatching signal %d to handler %s' % (signum, str(signal_cb)))
    return signal_cb(*cb_params) 
Example #22
Source File: EventDispatcher.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def signal(self, signum, frame):
        self.signals_pending.append(signum) 
Example #23
Source File: test_signal_handlers.py    From sanic with MIT License 5 votes vote down vote up
def set_loop(app, loop):
    global mock
    mock = MagicMock()
    if os.name == "nt":
        signal.signal = mock
    else:
        loop.add_signal_handler = mock 
Example #24
Source File: test_signal_handlers.py    From sanic with MIT License 5 votes vote down vote up
def test_windows_workaround():
    """Test Windows workaround (on any other OS)"""
    # At least some code coverage, even though this test doesn't work on
    # Windows...
    class MockApp:
        def __init__(self):
            self.is_stopping = False

        def stop(self):
            assert not self.is_stopping
            self.is_stopping = True

        def add_task(self, func):
            loop = asyncio.get_event_loop()
            self.stay_active_task = loop.create_task(func(self))

    async def atest(stop_first):
        app = MockApp()
        ctrlc_workaround_for_windows(app)
        await asyncio.sleep(0.05)
        if stop_first:
            app.stop()
            await asyncio.sleep(0.2)
        assert app.is_stopping == stop_first
        # First Ctrl+C: should call app.stop() within 0.1 seconds
        os.kill(os.getpid(), signal.SIGINT)
        await asyncio.sleep(0.2)
        assert app.is_stopping
        assert app.stay_active_task.result() == None
        # Second Ctrl+C should raise
        with pytest.raises(KeyboardInterrupt):
            os.kill(os.getpid(), signal.SIGINT)
        return "OK"

    # Run in our private loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    res = loop.run_until_complete(atest(False))
    assert res == "OK"
    res = loop.run_until_complete(atest(True))
    assert res == "OK" 
Example #25
Source File: test_multiprocessing.py    From sanic with MIT License 5 votes vote down vote up
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 
Example #26
Source File: plugins.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_handler(self, signal, listener=None):
        """Subscribe a handler for the given signal (number or name).

        If the optional 'listener' argument is provided, it will be
        subscribed as a listener for the given signal's channel.

        If the given signal name or number is not available on the current
        platform, ValueError is raised.
        """
        if isinstance(signal, text_or_bytes):
            signum = getattr(_signal, signal, None)
            if signum is None:
                raise ValueError('No such signal: %r' % signal)
            signame = signal
        else:
            try:
                signame = self.signals[signal]
            except KeyError:
                raise ValueError('No such signal: %r' % signal)
            signum = signal

        prev = _signal.signal(signum, self._handle_signal)
        self._previous_handlers[signum] = prev

        if listener is not None:
            self.bus.log('Listening for %s.' % signame)
            self.bus.subscribe(signame, listener) 
Example #27
Source File: gassistant.py    From google-assistant-hotword-raspi with MIT License 5 votes vote down vote up
def signal_handler(signal, frame):
    global interrupted
    interrupted = True 
Example #28
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 5 votes vote down vote up
def handle_sigterm(sig, frame):
    """
    handler for ctrl+c signal
    """
    raise(SystemExit) 
Example #29
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 5 votes vote down vote up
def handle_sighub(sig, frame):
    """
    handling SIGHUB signal for reload configuration
    Linux/macOS only
    """
    messenger.info('Reload config file')
    load_config() 
Example #30
Source File: test_server_events.py    From sanic with MIT License 5 votes vote down vote up
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