Python signal.SIGBREAK Examples

The following are 30 code examples of signal.SIGBREAK(). 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: _utils.py    From cotyledon with Apache License 2.0 7 votes vote down vote up
def __init__(self):
        # Setup signal fd, this allows signal to behave correctly
        if os.name == 'posix':
            self.signal_pipe_r, self.signal_pipe_w = os.pipe()
            self._set_nonblock(self.signal_pipe_r)
            self._set_nonblock(self.signal_pipe_w)
            signal.set_wakeup_fd(self.signal_pipe_w)

        self._signals_received = collections.deque()

        signal.signal(signal.SIGINT, signal.SIG_DFL)
        if os.name == 'posix':
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
            signal.signal(signal.SIGTERM, self._signal_catcher)
            signal.signal(signal.SIGALRM, self._signal_catcher)
            signal.signal(signal.SIGHUP, self._signal_catcher)
        else:
            # currently a noop on window...
            signal.signal(signal.SIGTERM, self._signal_catcher)
            # FIXME(sileht): should allow to catch signal CTRL_BREAK_EVENT,
            # but we to create the child process with CREATE_NEW_PROCESS_GROUP
            # to make this work, so current this is a noop for later fix
            signal.signal(signal.SIGBREAK, self._signal_catcher) 
Example #2
Source File: test_signal.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        checked = set()
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows.
            # Issue #18396, only for signals without a C-level handler.
            if signal.getsignal(sig) is not None:
                signal.signal(sig, signal.signal(sig, handler))
                checked.add(sig)
        # Issue #18396: Ensure the above loop at least tested *something*
        self.assertTrue(checked)

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #3
Source File: test_signal.py    From android_universal with MIT License 6 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        checked = set()
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows.
            # Issue #18396, only for signals without a C-level handler.
            if signal.getsignal(sig) is not None:
                signal.signal(sig, signal.signal(sig, handler))
                checked.add(sig)
        # Issue #18396: Ensure the above loop at least tested *something*
        self.assertTrue(checked)

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #4
Source File: test_signal.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        checked = set()
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows.
            # Issue #18396, only for signals without a C-level handler.
            if signal.getsignal(sig) is not None:
                signal.signal(sig, signal.signal(sig, handler))
                checked.add(sig)
        # Issue #18396: Ensure the above loop at least tested *something*
        self.assertTrue(checked)

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #5
Source File: subprocess42.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def terminate(self):
    """Tries to do something saner on Windows that the stdlib.

    Windows:
      self.detached/CREATE_NEW_PROCESS_GROUP determines what can be used:
      - If set, only SIGBREAK can be sent and it is sent to a single process.
      - If not set, in theory only SIGINT can be used and *all processes* in
         the processgroup receive it. In practice, we just kill the process.
      See http://msdn.microsoft.com/library/windows/desktop/ms683155.aspx
      The default on Windows is to call TerminateProcess() always, which is not
      useful.

    On Posix, always send SIGTERM.
    """
    try:
      if sys.platform == 'win32' and self.detached:
        return self.send_signal(signal.CTRL_BREAK_EVENT)
      super(Popen, self).terminate()
    except OSError:
      # The function will throw if the process terminated in-between. Swallow
      # this.
      pass 
Example #6
Source File: test_signal.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_signal_signal(self):
        WORKING_CASES = SUPPORTED_SIGNALS + [6]
        WEIRD_CASES = {
                    6: None,
                    2: signal.default_int_handler}
        for x in WORKING_CASES:
            #Ideal handler signature
            def a(signum, frame):
                return x

            ret_val = signal.signal(x, a)
            if x not in WEIRD_CASES.keys():
                self.assertEqual(ret_val, signal.SIG_DFL)
            else:
                self.assertEqual(ret_val, WEIRD_CASES[x])
            self.assertEqual(a, signal.getsignal(x))

        #Strange handler signatures
        class KNew(object):
            def __call__(self, *args, **kwargs):
                pass

        a = KNew()
        ret_val = signal.signal(signal.SIGBREAK, a)
        self.assertEqual(a, signal.getsignal(signal.SIGBREAK)) 
Example #7
Source File: test_signal.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        checked = set()
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows.
            # Issue #18396, only for signals without a C-level handler.
            if signal.getsignal(sig) is not None:
                signal.signal(sig, signal.signal(sig, handler))
                checked.add(sig)
        # Issue #18396: Ensure the above loop at least tested *something*
        self.assertTrue(checked)

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #8
Source File: popen_spawn.py    From pipenv with MIT License 6 votes vote down vote up
def kill(self, sig):
        '''Sends a Unix signal to the subprocess.

        Use constants from the :mod:`signal` module to specify which signal.
        '''
        if sys.platform == 'win32':
            if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
                sig = signal.CTRL_C_EVENT
            elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
                sig = signal.CTRL_BREAK_EVENT
            else:
                sig = signal.SIGTERM

        os.kill(self.proc.pid, sig) 
Example #9
Source File: test_signal.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_signal_signal(self):
        WORKING_CASES = SUPPORTED_SIGNALS + [6]
        WEIRD_CASES = {
                    6: None,
                    2: signal.default_int_handler}
        for x in WORKING_CASES:
            #Ideal handler signature
            def a(signum, frame):
                return x
            
            ret_val = signal.signal(x, a)
            if x not in WEIRD_CASES.keys():
                self.assertEqual(ret_val, signal.SIG_DFL)
            else:
                self.assertEqual(ret_val, WEIRD_CASES[x])
            self.assertEqual(a, signal.getsignal(x))
            
        #Strange handler signatures
        class KNew(object):
            def __call__(self, *args, **kwargs):
                pass
        
        a = KNew()
        ret_val = signal.signal(signal.SIGBREAK, a)
        self.assertEqual(a, signal.getsignal(signal.SIGBREAK)) 
Example #10
Source File: test_signal.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows
            signal.signal(sig, signal.signal(sig, handler))

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #11
Source File: utils.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def term_signal():
    """Gets the term signal for the os."""
    if os.name == 'nt':
        return signal.SIGBREAK
    else:
        return signal.SIGTERM 
Example #12
Source File: test_signal.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows
            signal.signal(sig, signal.signal(sig, handler))

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #13
Source File: common.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def exec_python(args):
  """Executes a python process, replacing the current process if possible.

  On Windows, it returns the child process code. The caller must exit at the
  earliest opportunity.
  """
  cmd = [sys.executable] + args
  if sys.platform not in ('cygwin', 'win32'):
    os.execv(cmd[0], cmd)
    return 1

  try:
    # On Windows, we cannot sanely exec() so shell out the child process
    # instead. But we need to forward any signal received that the bot may care
    # about. This means processes accumulate, sadly.
    # TODO(maruel): If stdin closes, it tells the child process that the parent
    # process died.
    proc = subprocess42.Popen(cmd, detached=True, stdin=subprocess42.PIPE)

    def handler(sig, _):
      logging.info('Got signal %s', sig)
      # Always send SIGTERM, which is properly translated.
      proc.send_signal(signal.SIGTERM)

    sig = signal.SIGBREAK if sys.platform == 'win32' else signal.SIGTERM
    with subprocess42.set_signal_handler([sig], handler):
      proc.wait()
      return proc.returncode
  except Exception as e:
    logging.exception('failed to start: %s', e)
    # Swallow the exception.
    return 1 
Example #14
Source File: test_signal.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_module_constants(self):
        self.assertEqual(signal.NSIG, 23)
        self.assertEqual(signal.SIGABRT, 22)
        self.assertEqual(signal.SIGBREAK, 21)
        self.assertEqual(signal.SIGFPE, 8)
        self.assertEqual(signal.SIGILL, 4)
        self.assertEqual(signal.SIGINT, 2)
        self.assertEqual(signal.SIGSEGV, 11)
        self.assertEqual(signal.SIGTERM, 15)
        self.assertEqual(signal.SIG_DFL, 0)
        self.assertEqual(signal.SIG_IGN, 1) 
Example #15
Source File: popen_spawn.py    From pipenv-sublime with MIT License 5 votes vote down vote up
def kill(self, sig):
        '''Sends a Unix signal to the subprocess.
        
        Use constants from the :mod:`signal` module to specify which signal.
        '''
        if sys.platform == 'win32':
            if sig in [signal.SIGINT, signal.CTRL_C_EVENT]:
                sig = signal.CTRL_C_EVENT
            elif sig in [signal.SIGBREAK, signal.CTRL_BREAK_EVENT]:
                sig = signal.CTRL_BREAK_EVENT
            else:
                sig = signal.SIGTERM

        os.kill(self.proc.pid, sig) 
Example #16
Source File: test_base.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_captureSIGBREAK(self):
        """
        ReactorBase's SIGBREAK handler saves the value of SIGBREAK to the
        _exitSignal attribute.
        """
        if not hasattr(signal, "SIGBREAK"):
            raise SkipTest("signal module does not have SIGBREAK")

        reactor = TestSpySignalCapturingReactor()
        reactor.sigBreak(signal.SIGBREAK, None)
        self.assertEquals(signal.SIGBREAK, reactor._exitSignal) 
Example #17
Source File: test_signal.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows
            signal.signal(sig, signal.signal(sig, handler))

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #18
Source File: test_signal.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_issue9324(self):
        # Updated for issue #10003, adding SIGBREAK
        handler = lambda x, y: None
        for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
                    signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
                    signal.SIGTERM):
            # Set and then reset a handler for signals that work on windows
            signal.signal(sig, signal.signal(sig, handler))

        with self.assertRaises(ValueError):
            signal.signal(-1, handler)

        with self.assertRaises(ValueError):
            signal.signal(7, handler) 
Example #19
Source File: test_signal.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_module_constants(self):
        self.assertEqual(signal.NSIG, 23)
        self.assertEqual(signal.SIGABRT, 22)
        self.assertEqual(signal.SIGBREAK, 21)
        self.assertEqual(signal.SIGFPE, 8)
        self.assertEqual(signal.SIGILL, 4)
        self.assertEqual(signal.SIGINT, 2)
        self.assertEqual(signal.SIGSEGV, 11)
        self.assertEqual(signal.SIGTERM, 15)
        self.assertEqual(signal.SIG_DFL, 0)
        self.assertEqual(signal.SIG_IGN, 1) 
Example #20
Source File: external_search_command.py    From misp42splunk with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #21
Source File: external_search_command.py    From SplunkAdmins with Apache License 2.0 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
                The arguments to the child process should start with the name of the command being run, but this is not
                enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
                This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
                the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #22
Source File: external_search_command.py    From vscode-extension-splunk with MIT License 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #23
Source File: external_search_command.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)
            sys.exit(p.returncode) 
Example #24
Source File: external_search_command.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)
            sys.exit(p.returncode) 
Example #25
Source File: external_search_command.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #26
Source File: spin.py    From vistir with ISC License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        # type: (Any, Any)
        """
        Get a spinner object or a dummy spinner to wrap a context.

        Keyword Arguments:
        :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
        :param str start_text: Text to start off the spinner with (default: {None})
        :param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
        :param bool nospin: If true, use the dummy spinner (default: {False})
        :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
        """

        self.handler = handler
        colorama.init()
        sigmap = {}  # type: TSignalMap
        if handler:
            sigmap.update({signal.SIGINT: handler, signal.SIGTERM: handler})
        handler_map = kwargs.pop("handler_map", {})
        if os.name == "nt":
            sigmap[signal.SIGBREAK] = handler
        else:
            sigmap[signal.SIGALRM] = handler
        if handler_map:
            sigmap.update(handler_map)
        spinner_name = kwargs.pop("spinner_name", "bouncingBar")
        start_text = kwargs.pop("start_text", None)
        _text = kwargs.pop("text", "Running...")
        kwargs["text"] = start_text if start_text is not None else _text
        kwargs["sigmap"] = sigmap
        kwargs["spinner"] = getattr(Spinners, spinner_name, "")
        write_to_stdout = kwargs.pop("write_to_stdout", True)
        self.stdout = kwargs.pop("stdout", sys.stdout)
        self.stderr = kwargs.pop("stderr", sys.stderr)
        self.out_buff = StringIO()
        self.write_to_stdout = write_to_stdout
        self.is_dummy = bool(yaspin is None)
        self._stop_spin = None  # type: Optional[threading.Event]
        self._hide_spin = None  # type: Optional[threading.Event]
        self._spin_thread = None  # type: Optional[threading.Thread]
        super(VistirSpinner, self).__init__(*args, **kwargs)
        if DISABLE_COLORS:
            colorama.deinit() 
Example #27
Source File: external_search_command.py    From misp42splunk with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
                The arguments to the child process should start with the name of the command being run, but this is not
                enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
                This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
                the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #28
Source File: external_search_command.py    From misp42splunk with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
            The arguments to the child process should start with the name of the command being run, but this is not
            enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
            This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
            the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode) 
Example #29
Source File: spin.py    From pipenv with MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        # type: (Any, Any)
        """
        Get a spinner object or a dummy spinner to wrap a context.

        Keyword Arguments:
        :param str spinner_name: A spinner type e.g. "dots" or "bouncingBar" (default: {"bouncingBar"})
        :param str start_text: Text to start off the spinner with (default: {None})
        :param dict handler_map: Handler map for signals to be handled gracefully (default: {None})
        :param bool nospin: If true, use the dummy spinner (default: {False})
        :param bool write_to_stdout: Writes to stdout if true, otherwise writes to stderr (default: True)
        """

        self.handler = handler
        colorama.init()
        sigmap = {}  # type: TSignalMap
        if handler:
            sigmap.update({signal.SIGINT: handler, signal.SIGTERM: handler})
        handler_map = kwargs.pop("handler_map", {})
        if os.name == "nt":
            sigmap[signal.SIGBREAK] = handler
        else:
            sigmap[signal.SIGALRM] = handler
        if handler_map:
            sigmap.update(handler_map)
        spinner_name = kwargs.pop("spinner_name", "bouncingBar")
        start_text = kwargs.pop("start_text", None)
        _text = kwargs.pop("text", "Running...")
        kwargs["text"] = start_text if start_text is not None else _text
        kwargs["sigmap"] = sigmap
        kwargs["spinner"] = getattr(Spinners, spinner_name, "")
        write_to_stdout = kwargs.pop("write_to_stdout", True)
        self.stdout = kwargs.pop("stdout", sys.stdout)
        self.stderr = kwargs.pop("stderr", sys.stderr)
        self.out_buff = StringIO()
        self.write_to_stdout = write_to_stdout
        self.is_dummy = bool(yaspin is None)
        self._stop_spin = None  # type: Optional[threading.Event]
        self._hide_spin = None  # type: Optional[threading.Event]
        self._spin_thread = None  # type: Optional[threading.Thread]
        super(VistirSpinner, self).__init__(*args, **kwargs)
        if DISABLE_COLORS:
            colorama.deinit() 
Example #30
Source File: external_search_command.py    From misp42splunk with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _execute(path, argv=None, environ=None):
            """ Executes an external search command.

            :param path: Path to the external search command.
            :type path: unicode

            :param argv: Argument list.
            :type argv: list or tuple
                The arguments to the child process should start with the name of the command being run, but this is not
                enforced. A value of :const:`None` specifies that the base name of path name :param:`path` should be used.

            :param environ: A mapping which is used to define the environment variables for the new process.
            :type environ: dict or None.
                This mapping is used instead of the current process’s environment. A value of :const:`None` specifies that
                the :data:`os.environ` mapping should be used.

            :return: None

            """
            search_path = os.getenv('PATH') if environ is None else environ.get('PATH')
            found = ExternalSearchCommand._search_path(path, search_path)

            if found is None:
                raise ValueError('Cannot find command on path: {}'.format(path))

            path = found
            logger.debug('starting command="%s", arguments=%s', path, argv)

            def terminate(signal_number, frame):
                sys.exit('External search command is terminating on receipt of signal={}.'.format(signal_number))

            def terminate_child():
                if p.pid is not None and p.returncode is None:
                    logger.debug('terminating command="%s", arguments=%d, pid=%d', path, argv, p.pid)
                    os.kill(p.pid, CTRL_BREAK_EVENT)

            p = Popen(argv, executable=path, env=environ, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            atexit.register(terminate_child)
            signal(SIGBREAK, terminate)
            signal(SIGINT, terminate)
            signal(SIGTERM, terminate)

            logger.debug('started command="%s", arguments=%s, pid=%d', path, argv, p.pid)
            p.wait()

            logger.debug('finished command="%s", arguments=%s, pid=%d, returncode=%d', path, argv, p.pid, p.returncode)

            if p.returncode != 0:
                sys.exit(p.returncode)