Python signal.signal() Examples

The following are 30 code examples for showing how to use signal.signal(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module signal , or try the search function .

Example 1
Project: svviz   Author: svviz   File: multiprocessor.py    License: MIT License 6 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
Project: BASS   Author: Cisco-Talos   File: cmdline.py    License: 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 3
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    License: MIT License 6 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
Project: cherrypy   Author: cherrypy   File: plugins.py    License: 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 5
Project: wio-cli   Author: Seeed-Studio   File: wio.py    License: MIT License 6 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 6
Project: rtp_cluster   Author: sippy   File: EventDispatcher.py    License: 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 7
Project: sanic   Author: huge-success   File: test_multiprocessing.py    License: MIT License 6 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 8
Project: sanic   Author: huge-success   File: compat.py    License: 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 9
Project: jawfish   Author: war-and-code   File: signals.py    License: 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 10
Project: jawfish   Author: war-and-code   File: test_break.py    License: 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 11
Project: jawfish   Author: war-and-code   File: test_break.py    License: 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 12
Project: jawfish   Author: war-and-code   File: test_break.py    License: 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 13
Project: jawfish   Author: war-and-code   File: test_break.py    License: 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 14
Project: dataflow   Author: tensorpack   File: concurrency.py    License: 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 15
Project: dataflow   Author: tensorpack   File: concurrency.py    License: 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 16
Project: incubator-spot   Author: apache   File: collector.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, datatype, topic, skip_conversion, **conf):
        self._logger          = logging.getLogger('SPOT.INGEST.COLLECTOR')
        self._logger.info('Initializing Distributed Collector process...')

        self._datatype        = datatype
        self._interval        = conf['ingestion_interval']
        self._isalive         = True
        self._process_opts    = conf['pipelines'][datatype]['process_opt']
        self._processes       = conf['collector_processes']
        self._producer_kwargs = conf['producer']
        self._skip_conversion = skip_conversion
        self._topic           = topic

        # .............................init FileObserver
        self.FileWatcher      = FileWatcher(**conf['file_watcher'])

        # .............................set up local staging area
        self._tmpdir          = mkdtemp(prefix='_DC.', dir=conf['pipelines'][datatype]['local_staging'])
        self._logger.info('Use directory "{0}" as local staging area.'.format(self._tmpdir))

        # .............................define a process pool object
        self._pool            = Pool(self._processes, _init_child, [self._tmpdir])
        self._logger.info('Master Collector will use {0} parallel processes.'
            .format(self._processes))

        signal.signal(signal.SIGUSR1, self.kill)
        self._logger.info('Initialization completed successfully!') 
Example 17
Project: incubator-spot   Author: apache   File: collector.py    License: Apache License 2.0 5 votes vote down vote up
def kill(self):
        '''
            Receive signal for termination from an external process.
        '''
        self._logger.info('Receiving a kill signal from an external process...')
        self._isalive = False 
Example 18
Project: incubator-spot   Author: apache   File: collector.py    License: Apache License 2.0 5 votes vote down vote up
def _init_child(tmpdir):
    '''
        Initialize new process from multiprocessing module's Pool.

    :param tmpdir: Path of local staging area.
    '''
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    # .................................for each process, create a isolated temp folder
    proc_dir = os.path.join(tmpdir, current_process().name)

    if not os.path.isdir(proc_dir):
        os.mkdir(proc_dir) 
Example 19
Project: RF-Monitor   Author: EarToEarOak   File: cli.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __on_exit(self, _signal=None, _frame=None):
        signal.signal(signal.SIGINT, self._signal)
        self._cancel = True 
Example 20
Project: RF-Monitor   Author: EarToEarOak   File: cli.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __on_scan_data(self, event):
        levels = numpy.log10(event['l'])
        levels *= 10

        noise = numpy.percentile(levels,
                                 self._dynP)

        for monitor in self._monitors:
            freq = monitor.get_frequency()
            if monitor.get_enabled():
                monitor.set_noise(noise)
                index = numpy.where(freq == event['f'])[0]
                signal = monitor.set_level(levels[index][0],
                                           event['timestamp'],
                                           self._location)

                if signal is not None:
                    signals = 'Signals: {}\r'.format(self.__count_signals() -
                                                     self._signalCount)
                    self.__std_out(signals, False)
                    if signal.end is not None:
                        recording = format_recording(freq, signal)
                        if self._pushUri is not None:
                            self._push.send(self._pushUri,
                                            recording)
                        if self._server is not None:
                            self._server.send(recording)
                        if self._json:
                            sys.stdout.write(recording + '\n') 
Example 21
Project: cherrypy   Author: cherrypy   File: plugins.py    License: 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 22
Project: cherrypy   Author: cherrypy   File: plugins.py    License: 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 23
Project: cherrypy   Author: cherrypy   File: _test_states_demo.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unsub_sig():
    cherrypy.log('unsubsig: %s' % cherrypy.config.get('unsubsig', False))
    if cherrypy.config.get('unsubsig', False):
        cherrypy.log('Unsubscribing the default cherrypy signal handler')
        cherrypy.engine.signal_handler.unsubscribe()
    try:
        from signal import signal, SIGTERM
    except ImportError:
        pass
    else:
        def old_term_handler(signum=None, frame=None):
            cherrypy.log('I am an old SIGTERM handler.')
            sys.exit(0)
        cherrypy.log('Subscribing the new one.')
        signal(SIGTERM, old_term_handler) 
Example 24
Project: gated-graph-transformer-network   Author: hexahedria   File: graceful_interrupt.py    License: MIT License 5 votes vote down vote up
def __init__(self, sig=signal.SIGINT):
        self.sig = sig 
Example 25
Project: gated-graph-transformer-network   Author: hexahedria   File: graceful_interrupt.py    License: MIT License 5 votes vote down vote up
def __enter__(self):

        self.interrupted = False
        self.released = False

        self.original_handler = signal.getsignal(self.sig)

        def handler(signum, frame):
            self.release()
            self.interrupted = True
            print("(Caught interrupt. Terminating when safe.... Press Ctrl-C again to force stop)")

        signal.signal(self.sig, handler)

        return self 
Example 26
Project: gated-graph-transformer-network   Author: hexahedria   File: graceful_interrupt.py    License: MIT License 5 votes vote down vote up
def release(self):

        if self.released:
            return False

        signal.signal(self.sig, self.original_handler)

        self.released = True

        return True 
Example 27
Project: sandsifter   Author: Battelle   File: sifter.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop(self):
        if self.process:
            try:
                os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
            except OSError:
                pass 
Example 28
Project: multibootusb   Author: mbusb   File: progressbar.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, maxval=None, widgets=None, term_width=None, poll=1,
                 left_justify=True, fd=sys.stderr):
        """Initializes a progress bar with sane defaults."""

        # Don't share a reference with any other progress bars
        if widgets is None:
            widgets = list(self._DEFAULT_WIDGETS)

        self.maxval = maxval
        self.widgets = widgets
        self.fd = fd
        self.left_justify = left_justify

        self.signal_set = False
        if term_width is not None:
            self.term_width = term_width
        else:
            try:
                self._handle_resize()
                signal.signal(signal.SIGWINCH, self._handle_resize)
                self.signal_set = True
            except (SystemExit, KeyboardInterrupt): raise
            except:
                self.term_width = self._env_size()

        self.__iterable = None
        self._update_widgets()
        self.currval = 0
        self.finished = False
        self.last_update_time = None
        self.poll = poll
        self.seconds_elapsed = 0
        self.start_time = None
        self.update_interval = 1
        self.next_update = 0 
Example 29
Project: multibootusb   Author: mbusb   File: progressbar.py    License: GNU General Public License v2.0 5 votes vote down vote up
def finish(self):
        """Puts the ProgressBar bar in the finished state."""

        if self.finished:
            return
        self.finished = True
        self.update(self.maxval)
        self.fd.write('\n')
        if self.signal_set:
            signal.signal(signal.SIGWINCH, signal.SIG_DFL) 
Example 30
Project: Random-Erasing   Author: zhunzhong07   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SigIntMixin, self).__init__(*args, **kwargs)
        signal(SIGINT, self._sigint_handler)