Python signal.Signals() Examples

The following are 30 code examples of signal.Signals(). 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: snekbox.py    From bot with MIT License 6 votes vote down vote up
def get_results_message(results: dict) -> Tuple[str, str]:
        """Return a user-friendly message and error corresponding to the process's return code."""
        stdout, returncode = results["stdout"], results["returncode"]
        msg = f"Your eval job has completed with return code {returncode}"
        error = ""

        if returncode is None:
            msg = "Your eval job has failed"
            error = stdout.strip()
        elif returncode == 128 + SIGKILL:
            msg = "Your eval job timed out or ran out of memory"
        elif returncode == 255:
            msg = "Your eval job has failed"
            error = "A fatal NsJail error occurred"
        else:
            # Try to append signal's name if one exists
            try:
                name = Signals(returncode - 128).name
                msg = f"{msg} ({name})"
            except ValueError:
                pass

        return msg, error 
Example #2
Source File: g910_gkey_mapper.py    From g910-gkey-macro-support with GNU General Public License v3.0 6 votes vote down vote up
def signal_handler(sig, frame):
    global program_running
    log.warning("Got signal, " + signal.Signals(sig).name + " terminating!")
    print("Got signal,", signal.Signals(sig).name, "terminating!")
    try:
        device.__exit__()
        log.info("Removed uinput device")
        print("Removed uinput device")
    except SystemExit:
        sys.exit(0)
    except Exception as e:
        print("Could not remove uinput device:",e)
        log.info("Could not remove uinput device:",e)

    # pid_handler.remove_pid()
    log.info("----------------------EXITING-----------------------")
    print("Exiting")
    program_running = False
    sys.exit(0) 
Example #3
Source File: utils.py    From loky with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_exitcode_name(exitcode):
    if sys.platform == "win32":
        # The exitcode are unreliable  on windows (see bpo-31863).
        # For this case, return UNKNOWN
        return "UNKNOWN"

    if exitcode < 0:
        try:
            import signal
            if sys.version_info > (3, 5):
                return signal.Signals(-exitcode).name

            # construct an inverse lookup table
            for v, k in signal.__dict__.items():
                if (v.startswith('SIG') and not v.startswith('SIG_') and
                        k == -exitcode):
                        return v
        except ValueError:
            return "UNKNOWN"
    elif exitcode != 255:
        # The exitcode are unreliable on forkserver were 255 is always returned
        # (see bpo-30589). For this case, return UNKNOWN
        return "EXIT"

    return "UNKNOWN" 
Example #4
Source File: test_cases.py    From agents-aea with Apache License 2.0 6 votes vote down vote up
def terminate_agents(
        cls,
        *subprocesses: subprocess.Popen,
        signal: signal.Signals = signal.SIGINT,
        timeout: int = 10,
    ) -> None:
        """
        Terminate agent subprocesses.
        Run from agent's directory.

        :param subprocesses: the subprocesses running the agents
        :param signal: the signal for interuption
        :param timeout: the timeout for interuption
        """
        if not subprocesses:
            subprocesses = tuple(cls.subprocesses)
        for process in subprocesses:
            sigint_crossplatform(process)
        for process in subprocesses:
            process.wait(timeout=timeout) 
Example #5
Source File: _compat.py    From poetry with MIT License 6 votes vote down vote up
def __str__(self):
            if self.returncode and self.returncode < 0:
                try:
                    return "Command '%s' died with %r." % (
                        self.cmd,
                        signal.Signals(-self.returncode),
                    )
                except ValueError:
                    return "Command '%s' died with unknown signal %d." % (
                        self.cmd,
                        -self.returncode,
                    )
            else:
                return "Command '%s' returned non-zero exit status %d." % (
                    self.cmd,
                    self.returncode,
                ) 
Example #6
Source File: seedsync.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def signal(self, signum: int, _):
        # noinspection PyUnresolvedReferences
        # Signals is a generated enum
        self.context.logger.info("Caught signal {}".format(signal.Signals(signum).name))
        raise ServiceExit() 
Example #7
Source File: errors.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def format_for_user_debugging(err: ModuleError) -> str:
    """
    Return a string for showing hapless users.

    Users should never see ModuleError. Only developers should see ModuleError,
    in logs and emailed alerts. But we need to show users _something_, and a
    hint of an error message greatly helps us talk with our users our debugging
    effort.
    """
    if isinstance(err, ModuleTimeoutError):
        return "timed out"
    elif isinstance(err, ModuleExitedError):
        try:
            # If the exit code is -9, for instance, return 'SIGTERM'
            exit_text = signal.Signals(-err.exit_code).name
        except ValueError:
            # Exit code 1 goes to "1"
            exit_text = "exit code %d" % err.exit_code
        # Usually, the last line of output is the one that differentiates it.
        # In particular, this is the "ValueError" line in a Python stack trace.
        for line in reversed(err.log.split("\n")):
            # Ignore newlines at the end of output.
            if line:
                last_line = line
                break
        else:
            last_line = None
        if last_line:
            # "exit code 1: ValueError: invalid JSON..."
            return "%s: %s" % (exit_text, last_line or "(empty)")
        else:
            # "SIGSEGV"
            return exit_text
    else:
        message = str(err)
        if message:
            return type(err).__name__ + ": " + message
        else:
            return type(err).__name__ 
Example #8
Source File: test_signal.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_enums(self):
        for name in dir(signal):
            sig = getattr(signal, name)
            if name in {'SIG_DFL', 'SIG_IGN'}:
                self.assertIsInstance(sig, signal.Handlers)
            elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}:
                self.assertIsInstance(sig, signal.Sigmasks)
            elif name.startswith('SIG') and not name.startswith('SIG_'):
                self.assertIsInstance(sig, signal.Signals)
            elif name.startswith('CTRL_'):
                self.assertIsInstance(sig, signal.Signals)
                self.assertEqual(sys.platform, "win32") 
Example #9
Source File: test_signal.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_sigpending(self):
        code = """if 1:
            import os
            import signal

            def handler(signum, frame):
                1/0

            signum = signal.SIGUSR1
            signal.signal(signum, handler)

            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            os.kill(os.getpid(), signum)
            pending = signal.sigpending()
            for sig in pending:
                assert isinstance(sig, signal.Signals), repr(pending)
            if pending != {signum}:
                raise Exception('%s != {%s}' % (pending, signum))
            try:
                signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
            except ZeroDivisionError:
                pass
            else:
                raise Exception("ZeroDivisionError not raised")
        """
        assert_python_ok('-c', code) 
Example #10
Source File: test_signal.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_sigwait(self):
        self.wait_helper(signal.SIGALRM, '''
        def test(signum):
            signal.alarm(1)
            received = signal.sigwait([signum])
            assert isinstance(received, signal.Signals), received
            if received != signum:
                raise Exception('received %s, not %s' % (received, signum))
        ''') 
Example #11
Source File: utils.py    From aria2p with ISC License 5 votes vote down vote up
def __init__(self, signals: List[str]) -> None:
        """
        Initialization method.

        Args:
            signals: List of signals names as found in the ``signal`` module (example: SIGTERM).
        """
        logger.debug("Signal handler: handling signals " + ", ".join(signals))
        self.triggered = False
        for sig in signals:
            try:
                signal.signal(signal.Signals[sig], self.trigger)
            except ValueError as error:
                logger.error(f"Failed to setup signal handler for {sig}: {error}") 
Example #12
Source File: utils.py    From aria2p with ISC License 5 votes vote down vote up
def trigger(self, signum, frame) -> None:
        """Mark this instance as 'triggered' (a specified signal was received)."""
        logger.debug(f"Signal handler: caught signal {signal.Signals(signum).name} ({signum})")
        self.triggered = True 
Example #13
Source File: test_pgnotify.py    From pgnotify with The Unlicense 5 votes vote down vote up
def test_pg_notify(db):
    for n in await_pg_notifications(
        db,
        ["hello", "hello2"],
        timeout=0.01,
        yield_on_timeout=True,
        handle_signals=SIGNALS_TO_HANDLE,
    ):
        if n is None:
            with S(db) as s:
                s.execute("notify hello, 'here is my message'")

        elif isinstance(n, int):
            sig = signal.Signals(n)
            assert sig.name == "SIGINT"
            assert n == signal.SIGINT
            break

        else:
            assert n.channel == "hello"
            assert n.payload == "here is my message"
            os.kill(os.getpid(), signal.SIGINT)

    with raises(KeyboardInterrupt):
        for n in await_pg_notifications(
            db, "hello", timeout=0.1, yield_on_timeout=True
        ):
            os.kill(os.getpid(), signal.SIGINT) 
Example #14
Source File: test_pgnotify.py    From pgnotify with The Unlicense 5 votes vote down vote up
def test_dynamic_timeout(db):
    def get_timeout():
        return -1

    for n in await_pg_notifications(
        db,
        ["hello", "hello2"],
        timeout=get_timeout,
        yield_on_timeout=True,
        notifications_as_list=True,
        handle_signals=SIGNALS_TO_HANDLE,
    ):
        if n is None:
            with S(db) as s:
                s.execute("notify hello, 'here is my message'")

        elif isinstance(n, int):
            sig = signal.Signals(n)
            assert sig.name == "SIGINT"
            assert n == signal.SIGINT
            break

        else:
            assert len(n) == 1
            _n = n[0]
            assert _n.channel == "hello"
            assert _n.payload == "here is my message"
            os.kill(os.getpid(), signal.SIGINT)

    with raises(KeyboardInterrupt):
        for n in await_pg_notifications(
            db, "hello", timeout=0.1, yield_on_timeout=True
        ):
            os.kill(os.getpid(), signal.SIGINT) 
Example #15
Source File: running.py    From kopf with MIT License 5 votes vote down vote up
def _stop_flag_checker(
        signal_flag: asyncio_Future,
        stop_flag: Optional[primitives.Flag],
) -> None:
    """
    A top-level task for external stopping by setting a stop-flag. Once set,
    this task will exit, and thus all other top-level tasks will be cancelled.
    """

    # Selects the flags to be awaited (if set).
    flags = []
    if signal_flag is not None:
        flags.append(signal_flag)
    if stop_flag is not None:
        flags.append(asyncio.create_task(primitives.wait_flag(stop_flag)))

    # Wait until one of the stoppers is set/raised.
    try:
        done, pending = await asyncio.wait(flags, return_when=asyncio.FIRST_COMPLETED)
        future = done.pop()
        result = await future
    except asyncio.CancelledError:
        pass  # operator is stopping for any other reason
    else:
        if result is None:
            logger.info("Stop-flag is raised. Operator is stopping.")
        elif isinstance(result, signal.Signals):
            logger.info("Signal %s is received. Operator is stopping.", result.name)
        else:
            logger.info("Stop-flag is set to %r. Operator is stopping.", result) 
Example #16
Source File: delayed_interrupt.py    From mathlib-tools with Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self.signal_received = {}
        self.old_handlers = {}
        for sig in self.sigs:
            self.signal_received[sig] = False
            self.old_handlers[sig] = signal.getsignal(sig)
            def handler(s, frame):
                self.signal_received[sig] = (s, frame)
                # Note: in Python 3.5, you can use signal.Signals(sig).name
                logging.info('Signal %s received. Delaying KeyboardInterrupt.' % sig)
            self.old_handlers[sig] = signal.getsignal(sig)
            signal.signal(sig, handler) 
Example #17
Source File: subprocess.py    From android_universal with MIT License 5 votes vote down vote up
def __str__(self):
        if self.returncode and self.returncode < 0:
            try:
                return "Command '%s' died with %r." % (
                        self.cmd, signal.Signals(-self.returncode))
            except ValueError:
                return "Command '%s' died with unknown signal %d." % (
                        self.cmd, -self.returncode)
        else:
            return "Command '%s' returned non-zero exit status %d." % (
                    self.cmd, self.returncode) 
Example #18
Source File: test_signal.py    From android_universal with MIT License 5 votes vote down vote up
def test_enums(self):
        for name in dir(signal):
            sig = getattr(signal, name)
            if name in {'SIG_DFL', 'SIG_IGN'}:
                self.assertIsInstance(sig, signal.Handlers)
            elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}:
                self.assertIsInstance(sig, signal.Sigmasks)
            elif name.startswith('SIG') and not name.startswith('SIG_'):
                self.assertIsInstance(sig, signal.Signals)
            elif name.startswith('CTRL_'):
                self.assertIsInstance(sig, signal.Signals)
                self.assertEqual(sys.platform, "win32") 
Example #19
Source File: test_signal.py    From android_universal with MIT License 5 votes vote down vote up
def test_sigpending(self):
        code = """if 1:
            import os
            import signal

            def handler(signum, frame):
                1/0

            signum = signal.SIGUSR1
            signal.signal(signum, handler)

            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            os.kill(os.getpid(), signum)
            pending = signal.sigpending()
            for sig in pending:
                assert isinstance(sig, signal.Signals), repr(pending)
            if pending != {signum}:
                raise Exception('%s != {%s}' % (pending, signum))
            try:
                signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
            except ZeroDivisionError:
                pass
            else:
                raise Exception("ZeroDivisionError not raised")
        """
        assert_python_ok('-c', code) 
Example #20
Source File: test_signal.py    From android_universal with MIT License 5 votes vote down vote up
def test_sigwait(self):
        self.wait_helper(signal.SIGALRM, '''
        def test(signum):
            signal.alarm(1)
            received = signal.sigwait([signum])
            assert isinstance(received, signal.Signals), received
            if received != signum:
                raise Exception('received %s, not %s' % (received, signum))
        ''') 
Example #21
Source File: scalene.py    From scalene with Apache License 2.0 5 votes vote down vote up
def cpu_signal_handler(
        signum: Union[Callable[[Signals, FrameType], None], int, Handlers, None],
        this_frame: FrameType,
    ) -> None:
        if Scalene.__in_signal_handler.acquire(blocking=False):
            Scalene.cpu_signal_handler_helper(signum, this_frame)
            Scalene.__in_signal_handler.release() 
Example #22
Source File: scalene.py    From scalene with Apache License 2.0 5 votes vote down vote up
def malloc_signal_handler(
        signum: Union[Callable[[Signals, FrameType], None], int, Handlers, None],
        this_frame: FrameType,
    ) -> None:
        """Handle malloc events."""
        if Scalene.__in_signal_handler.acquire(blocking=False):
            Scalene.allocation_signal_handler(signum, this_frame)
            Scalene.__in_signal_handler.release() 
Example #23
Source File: scalene.py    From scalene with Apache License 2.0 5 votes vote down vote up
def free_signal_handler(
        signum: Union[Callable[[Signals, FrameType], None], int, Handlers, None],
        this_frame: FrameType,
    ) -> None:
        """Handle free events."""
        if Scalene.__in_signal_handler.acquire(blocking=False):
            Scalene.allocation_signal_handler(signum, this_frame)
            Scalene.__in_signal_handler.release() 
Example #24
Source File: scalene.py    From scalene with Apache License 2.0 5 votes vote down vote up
def memcpy_event_signal_handler(
        signum: Union[Callable[[Signals, FrameType], None], int, Handlers, None],
        frame: FrameType,
    ) -> None:
        """Handles memcpy events."""
        if not Scalene.__in_signal_handler.acquire(blocking=False):
            return

        new_frames = Scalene.compute_frames_to_record(frame)
        if not new_frames:
            Scalene.__in_signal_handler.release()
            return

        # Process the input array.
        arr: List[Tuple[int, int]] = []
        try:
            with open(Scalene.__memcpy_signal_filename, "r") as mfile:
                for count_str in mfile:
                    count_str = count_str.rstrip()
                    (memcpy_time_str, count_str2) = count_str.split(",")
                    arr.append((int(memcpy_time_str), int(count_str2)))
        except FileNotFoundError:
            pass
        try:
            os.remove(Scalene.__memcpy_signal_filename)
        except FileNotFoundError:
            pass
        arr.sort()

        for item in arr:
            _memcpy_time, count = item
            for (the_frame, _tident, _orig_frame) in new_frames:
                fname = Filename(the_frame.f_code.co_filename)
                line_no = LineNumber(the_frame.f_lineno)
                bytei = ByteCodeIndex(the_frame.f_lasti)
                # Add the byte index to the set for this line.
                Scalene.__bytei_map[fname][line_no].add(bytei)
                Scalene.__memcpy_samples[fname][line_no] += count

        Scalene.__in_signal_handler.release() 
Example #25
Source File: shell.py    From shellen with MIT License 5 votes vote down vote up
def run(self):
        shellcode = self.last_shellcode()
        if not shellcode:
            cprint('\n<red,bold>[-]</> Assemble or disassemble something first!\n')
            return

        result = native.run(shellcode)
        if result < 0:
            sig_info = signal.Signals(-result)
            cprint('\n<red,bold>[-]</> Exited with signal <white>{}</> (<white,underline>{}</>)\n'.format(sig_info.name, sig_info.value))
        elif result == 0:
            cprint('\n<green>[+]</> Exited with status code 0.\n')
        else: # result > 0
            cprint('\n<yellow>[*]</> Exited with status code {}.\n'.format(result)) 
Example #26
Source File: subprocess.py    From Imogen with MIT License 5 votes vote down vote up
def __str__(self):
        if self.returncode and self.returncode < 0:
            try:
                return "Command '%s' died with %r." % (
                        self.cmd, signal.Signals(-self.returncode))
            except ValueError:
                return "Command '%s' died with unknown signal %d." % (
                        self.cmd, -self.returncode)
        else:
            return "Command '%s' returned non-zero exit status %d." % (
                    self.cmd, self.returncode) 
Example #27
Source File: abstract_job_model.py    From black-widow with GNU General Public License v3.0 5 votes vote down vote up
def status_name(self) -> str:
        return signal.Signals(self.status).name 
Example #28
Source File: utils.py    From AmbroBot with GNU General Public License v3.0 5 votes vote down vote up
def signal_handler(signal_number, frame):
    sig_name = signal.Signals(signal_number).name
    logger.info(f'Captured signal number {signal_number}. Name: {sig_name}') 
Example #29
Source File: generic_utils.py    From videoflow with MIT License 5 votes vote down vote up
def __enter__(self):
        self.signal_received = {}
        self.old_handlers = {}
        for sig in self.sigs:
            self.signal_received[sig] = False
            self.old_handlers[sig] = signal.getsignal(sig)
            def handler(s, frame):
                self.signal_received[sig] = (s, frame)
                # Note: in Python 3.5, you can use signal.Signals(sig).name
            self.old_handlers[sig] = signal.getsignal(sig)
            signal.signal(sig, handler) 
Example #30
Source File: worker.py    From arq with MIT License 5 votes vote down vote up
def _add_signal_handler(self, signum: Signals, handler: Callable[[Signals], None]) -> None:
        try:
            self.loop.add_signal_handler(signum, partial(handler, signum))
        except NotImplementedError:  # pragma: no cover
            logger.debug('Windows does not support adding a signal handler to an eventloop')