当前位置: 首页>>代码示例>>Python>>正文


Python Popen.terminate方法代码示例

本文整理汇总了Python中psutil.Popen.terminate方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.terminate方法的具体用法?Python Popen.terminate怎么用?Python Popen.terminate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在psutil.Popen的用法示例。


在下文中一共展示了Popen.terminate方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_get_info

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
    def test_get_info(self):
        worker = Popen(["python -c 'import time;time.sleep(5)'"], shell=True)
        try:
            info = get_info(worker)
        finally:
            worker.terminate()

        self.assertTrue(isinstance(info["pid"], int))
        self.assertEqual(info["nice"], 0)
开发者ID:nightshade427,项目名称:circus,代码行数:11,代码来源:test_util.py

示例2: test_get_info

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
    def test_get_info(self):

        worker = Popen(['top'], shell=True)
        try:
            info = get_info(worker)
        finally:
            worker.terminate()

        self.assertTrue(isinstance(info['pid'], int))
        self.assertEqual(info['nice'], 0)
开发者ID:msabramo,项目名称:circus,代码行数:12,代码来源:test_util.py

示例3: test_get_info

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
    def test_get_info(self):
        worker = Popen(["python", "-c", SLEEP % 5])
        try:
            info = get_info(worker)
        finally:
            worker.terminate()

        self.assertTrue(isinstance(info['pid'], int))

        if IS_WINDOWS:
            self.assertEqual(info['nice'], psutil.NORMAL_PRIORITY_CLASS)
        else:
            self.assertEqual(info['nice'], 0)
开发者ID:BrainBot,项目名称:circus,代码行数:15,代码来源:test_util.py

示例4: cmd

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
def cmd(command, user=None, input=None, cli_input=None, cli_output=False, communicate=True,
        timeout=None, fail=True, log=None, tries=1, delay_min=5, delay_max=10, **kwargs):
    """
    Calls the `command` and returns a dictionary with process, stdout, stderr, and the returncode.

    Returned returncode, stdout and stderr will be None if `communicate` is set to False.

    :param user: If set, this will use ``sudo -u <user> ...`` to execute `command` as `user`.
    :type user: unicode
    :param input: If set, sended to stdin (if `communicate` is True).
    :type input: unicode
    :param cli_input: If set, sended to stdin (no condition).
    :type cli_input: unicode
    :param cli_output: Set to True to output (in real-time) stdout to stdout and stderr to stderr.
    :type cli_output: bool
    :param fail: Set to False to avoid the exception `subprocess.CalledProcessError`.
    :type fail: bool
    :param log: A function to log/print details about what is executed/any failure, can be a logger.
    :type log: callable, logging.Logger
    :param communicate: Set to True to communicate with the process, this is a locking call
                        (if timeout is None).
    :type communicate: bool
    :param timeout: Time-out for the communication with the process, in seconds.
    :type timeout: float
    :param tries: How many times you want the command to be retried ?
    :type tries: int
    :param delay_min: Minimum delay to sleep after every attempt communicate must be True.
    :type delay: float, int
    :param delay_max: Maximum delay to sleep after every attempt communicate must be True.
    :type delay: float, int

    * Delay will be a random number in range (`delay_min`, `delay_max`)
    * Set kwargs with any argument of the :mod:`subprocess`.Popen constructor excepting
      stdin, stdout and stderr.

    """
    # convert log argument to logging functions
    log_debug = log_warning = log_exception = None
    if isinstance(log, logging.Logger):
        log_debug, log_warning, log_exception = log.debug, log.warning, log.exception
    elif hasattr(log, '__call__'):
        log_debug = log_warning = log_exception = log
    # create a list and a string of the arguments
    if isinstance(command, string_types):
        if user is not None:
            command = 'sudo -u {0} {1}'.format(user, command)
        args_list, args_string = shlex.split(to_bytes(command)), command
    else:
        if user is not None:
            command = ['sudo', '-u', user] + command
        args_list = [to_bytes(a) for a in command if a is not None]
        args_string = ' '.join([to_unicode(a) for a in command if a is not None])
    # log the execution
    if log_debug:
        log_debug('Execute {0}{1}{2}'.format(
            '' if input is None else 'echo {0}|'.format(repr(input)),
            args_string,
            '' if cli_input is None else ' < {0}'.format(repr(cli_input))))

    for trial in xrange(tries):  # noqa
        # create the sub-process
        try:
            process = Popen(
                args_list,
                stdin=subprocess.PIPE,
                stdout=None if cli_output else subprocess.PIPE,
                stderr=None if cli_output else subprocess.PIPE, **kwargs)
        except OSError as e:
            # unable to execute the program (e.g. does not exist)
            if log_exception:
                log_exception(e)
            if fail:
                raise
            return {'process': None, 'stdout': '', 'stderr': e, 'returncode': 2}
        # write to stdin (answer to questions, ...)
        if cli_input is not None:
            process.stdin.write(to_bytes(cli_input))
            process.stdin.flush()
        # interact with the process and wait for the process to terminate
        if communicate:
            data = {}

            # thanks http://stackoverflow.com/questions/1191374/subprocess-with-timeout
            def communicate_with_timeout(data=None):
                data['stdout'], data['stderr'] = process.communicate(input=input)
            thread = threading.Thread(target=communicate_with_timeout, kwargs={'data': data})
            thread.start()
            thread.join(timeout=timeout)
            if thread.is_alive():
                try:
                    process.terminate()
                    thread.join()
                except OSError as e:
                    # Manage race condition with process that may terminate just after the call to
                    # thread.is_alive() !
                    if e.errno != errno.ESRCH:
                        raise
            stdout, stderr = data['stdout'], data['stderr']
        else:
            # get a return code that may be None of course ...
#.........这里部分代码省略.........
开发者ID:davidfischer-ch,项目名称:pytoolbox,代码行数:103,代码来源:subprocess.py

示例5: Process

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]

#.........这里部分代码省略.........
        logger.debug("process args: %s", args)
        return args

    @debuglog
    def poll(self):
        return self._worker.poll()

    @debuglog
    def is_alive(self):
        return self.poll() is None

    @debuglog
    def send_signal(self, sig):
        """Sends a signal **sig** to the process."""
        logger.debug("sending signal %s to %s" % (sig, self.pid))
        return self._worker.send_signal(sig)

    @debuglog
    def stop(self):
        """Stop the process and close stdout/stderr

        If the corresponding process is still here
        (normally it's already killed by the watcher),
        a SIGTERM is sent, then a SIGKILL after 1 second.

        The shutdown process (SIGTERM then SIGKILL) is
        normally taken by the watcher. So if the process
        is still there here, it's a kind of bad behavior
        because the graceful timeout won't be respected here.
        """
        try:
            try:
                if self._worker.poll() is None:
                    return self._worker.terminate()
            finally:
                if self._worker.stderr is not None:
                    self._worker.stderr.close()
                if self._worker.stdout is not None:
                    self._worker.stdout.close()
        except NoSuchProcess:
            pass

    def age(self):
        """Return the age of the process in seconds."""
        return time.time() - self.started

    def info(self):
        """Return process info.

        The info returned is a mapping with these keys:

        - **mem_info1**: Resident Set Size Memory in bytes (RSS)
        - **mem_info2**: Virtual Memory Size in bytes (VMS).
        - **cpu**: % of cpu usage.
        - **mem**: % of memory usage.
        - **ctime**: process CPU (user + system) time in seconds.
        - **pid**: process id.
        - **username**: user name that owns the process.
        - **nice**: process niceness (between -20 and 20)
        - **cmdline**: the command line the process was run with.
        """
        try:
            info = get_info(self._worker)
        except NoSuchProcess:
            return "No such process (stopped?)"
开发者ID:amarandon,项目名称:circus,代码行数:69,代码来源:process.py

示例6: Process

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]

#.........这里部分代码省略.........
        return self._worker.returncode

    @debuglog
    def poll(self):
        return self._worker.poll()

    @debuglog
    def is_alive(self):
        return self.poll() is None

    @debuglog
    def send_signal(self, sig):
        """Sends a signal **sig** to the process."""
        logger.debug("sending signal %s to %s" % (sig, self.pid))
        return self._worker.send_signal(sig)

    @debuglog
    def stop(self):
        """Stop the process and close stdout/stderr

        If the corresponding process is still here
        (normally it's already killed by the watcher),
        a SIGTERM is sent, then a SIGKILL after 1 second.

        The shutdown process (SIGTERM then SIGKILL) is
        normally taken by the watcher. So if the process
        is still there here, it's a kind of bad behavior
        because the graceful timeout won't be respected here.
        """
        try:
            try:
                if self.is_alive():
                    try:
                        return self._worker.terminate()
                    except AccessDenied:
                        # It can happen on Windows if the process
                        # dies after poll returns (unlikely)
                        pass
            finally:
                self.close_output_channels()
        except NoSuchProcess:
            pass

    def close_output_channels(self):
        if self._worker.stderr is not None:
            self._worker.stderr.close()
        if self._worker.stdout is not None:
            self._worker.stdout.close()

    def wait(self, timeout=None):
        """
        Wait for the process to terminate, in the fashion
        of waitpid.

        Accepts a timeout in seconds.
        """
        self._worker.wait(timeout)

    def age(self):
        """Return the age of the process in seconds."""
        return time.time() - self.started

    def info(self):
        """Return process info.

        The info returned is a mapping with these keys:
开发者ID:ChaoticMind,项目名称:circus,代码行数:70,代码来源:process.py

示例7: Process

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]

#.........这里部分代码省略.........
        if args is not None:
            if isinstance(args, str):
                args_ = shlex.split(bytestring(args))
            else:
                args_ = args[:]

            args_ = shlex.split(bytestring(cmd)) + args_
        else:
            args_ = shlex.split(bytestring(cmd))

        logger.debug('Running %r' % ' '.join(args_))

        self._worker = Popen(args_, cwd=self.working_dir,
                             shell=self.shell, preexec_fn=preexec_fn,
                             env=self.env, close_fds=True, stdout=PIPE,
                             stderr=PIPE, executable=executable)

        self.started = time.time()

    @debuglog
    def poll(self):
        return self._worker.poll()

    @debuglog
    def send_signal(self, sig):
        """Sends a signal **sig** to the process."""
        return self._worker.send_signal(sig)

    @debuglog
    def stop(self):
        """Terminate the process."""
        try:
            if self._worker.poll() is None:
                return self._worker.terminate()
        finally:
            self._worker.stderr.close()
            self._worker.stdout.close()

    def age(self):
        """Return the age of the process in seconds."""
        return time.time() - self.started

    def info(self):
        """Return process info.

        The info returned is a mapping with these keys:

        - **mem_info1**: Resident Set Size Memory in bytes (RSS)
        - **mem_info2**: Virtual Memory Size in bytes (VMS).
        - **cpu**: % of cpu usage.
        - **mem**: % of memory usage.
        - **ctime**: process CPU (user + system) time in seconds.
        - **pid**: process id.
        - **username**: user name that owns the process.
        - **nice**: process niceness (between -20 and 20)
        - **cmdline**: the command line the process was run with.
        """
        try:
            info = get_info(self._worker)
        except NoSuchProcess:
            return "No such process (stopped?)"

        info["children"] = []
        for child in self._worker.get_children():
            info["children"].append(get_info(child))
开发者ID:crashekar,项目名称:circus,代码行数:69,代码来源:process.py

示例8: Fly

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
class Fly(object):
    def __init__(self, wid, cmd, working_dir, shell, uid=None, gid=None, env=None):
        self.wid = wid
        self.working_dir = working_dir
        self.shell = shell
        self.env = env
        self.cmd = cmd.replace("$WID", str(self.wid))

        self.uid = to_uid(uid)
        self.gid = to_gid(gid)

        def preexec_fn():
            os.setsid()
            if self.gid:
                try:
                    os.setgid(self.gid)
                except OverflowError:
                    if not ctypes:
                        raise
                    # versions of python < 2.6.2 don't manage unsigned int for
                    # groups like on osx or fedora
                    os.setgid(-ctypes.c_int(-self.gid).value)

            if self.uid:
                os.setuid(self.uid)

        self._worker = Popen(
            self.cmd.split(),
            cwd=self.working_dir,
            shell=self.shell,
            preexec_fn=preexec_fn,
            env=self.env,
            close_fds=True,
        )
        self.started = time.time()

    def poll(self):
        return self._worker.poll()

    def send_signal(self, sig):
        return self._worker.send_signal(sig)

    def stop(self):
        if self._worker.poll() is None:
            return self._worker.terminate()

    def age(self):
        return time.time() - self.started

    def info(self):
        """ return process info """
        info = _INFOLINE % get_info(self._worker)
        lines = ["%s: %s" % (self.wid, info)]

        for child in self._worker.get_children():
            info = _INFOLINE % get_info(child)
            lines.append("   %s" % info)

        return "\n".join(lines)

    def children(self):
        return ",".join(["%s" % child.pid for child in self._worker.get_children()])

    def send_signal_child(self, pid, signum):
        pids = [child.pid for child in self._worker.get_children()]
        if pid in pids:
            child.send_signal(signum)
            return "ok"
        else:
            return "error: child not found"

    def send_signal_children(self, signum):
        for child in self._worker.get_children():
            child.send_signal(signum)
        return "ok"

    @property
    def pid(self):
        return self._worker.pid
开发者ID:msabramo,项目名称:circus,代码行数:81,代码来源:fly.py

示例9: Process

# 需要导入模块: from psutil import Popen [as 别名]
# 或者: from psutil.Popen import terminate [as 别名]
class Process(object):
    """Wraps a process.

    Options:

    - **wid**: the process unique identifier. This value will be used to
      replace the *$WID* string in the command line if present.

    - **cmd**: the command to run. May contain *$WID*, which will be
      replaced by **wid**.

    - **working_dir**: the working directory to run the command in. If
      not provided, will default to the current working directory.

    - **shell**: if *True*, will run the command in the shell
      environment. *False* by default. **warning: this is a
      security hazard**.

    - **uid**: if given, is the user id or name the command should run
      with. The current uid is the default.

    - **gid**: if given, is the group id or name the command should run
      with. The current gid is the default.

    - **env**: a mapping containing the environment variables the command
      will run with. Optional.
    """
    def __init__(self, wid, cmd, working_dir=None, shell=False, uid=None,
                 gid=None, env=None):
        self.wid = wid
        if working_dir is None:
            self.working_dir = get_working_dir()
        else:
            self.working_dir = working_dir
        self.shell = shell
        self.env = env
        self.cmd = cmd.replace('$WID', str(self.wid))
        if uid is None:
            self.uid = None
        else:
            self.uid = to_uid(uid)

        if gid is None:
            self.gid = None
        else:
            self.gid = to_gid(gid)

        def preexec_fn():
            os.setsid()
            if self.gid:
                try:
                    os.setgid(self.gid)
                except OverflowError:
                    if not ctypes:
                        raise
                    # versions of python < 2.6.2 don't manage unsigned int for
                    # groups like on osx or fedora
                    os.setgid(-ctypes.c_int(-self.gid).value)

            if self.uid:
                os.setuid(self.uid)

        self._worker = Popen(self.cmd.split(), cwd=self.working_dir,
                             shell=self.shell, preexec_fn=preexec_fn,
                             env=self.env, close_fds=True, stdout=PIPE,
                             stderr=PIPE)
        self.started = time.time()

    @debuglog
    def poll(self):
        return self._worker.poll()

    @debuglog
    def send_signal(self, sig):
        """Sends a signal **sig** to the process."""
        return self._worker.send_signal(sig)

    @debuglog
    def stop(self):
        """Terminate the process."""
        if self._worker.poll() is None:
            return self._worker.terminate()

    def age(self):
        """Return the age of the process in seconds."""
        return time.time() - self.started

    def info(self):
        """Return process info.

        The info returned is a mapping with these keys:

        - **mem_info1**: Resident Set Size Memory in bytes (RSS)
        - **mem_info2**: Virtual Memory Size in bytes (VMS).
        - **cpu**: % of cpu usage.
        - **mem**: % of memory usage.
        - **ctime**: process CPU (user + system) time in seconds.
        - **pid**: process id.
        - **username**: user name that owns the process.
        - **nice**: process niceness (between -20 and 20)
#.........这里部分代码省略.........
开发者ID:fetep,项目名称:circus,代码行数:103,代码来源:process.py


注:本文中的psutil.Popen.terminate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。