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


Python psutil.Popen方法代码示例

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


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

示例1: test_misc

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def test_misc(self):
        # XXX this test causes a ResourceWarning on Python 3 because
        # psutil.__subproc instance doesn't get propertly freed.
        # Not sure what to do though.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.name()
            proc.cpu_times()
            proc.stdin
            self.assertTrue(dir(proc))
            self.assertRaises(AttributeError, getattr, proc, 'foo')
            proc.terminate()
        if POSIX:
            self.assertEqual(proc.wait(5), -signal.SIGTERM)
        else:
            self.assertEqual(proc.wait(5), signal.SIGTERM) 
开发者ID:giampaolo,项目名称:psutil,代码行数:19,代码来源:test_process.py

示例2: test_cli_webserver_foreground

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def test_cli_webserver_foreground(self):
        with mock.patch.dict(
            "os.environ",
            AIRFLOW__CORE__DAGS_FOLDER="/dev/null",
            AIRFLOW__CORE__LOAD_EXAMPLES="False",
            AIRFLOW__WEBSERVER__WORKERS="1"
        ):
            # Run webserver in foreground and terminate it.
            proc = subprocess.Popen(["airflow", "webserver"])
            self.assertEqual(None, proc.poll())

        # Wait for process
        sleep(10)

        # Terminate webserver
        proc.terminate()
        # -15 - the server was stopped before it started
        #   0 - the server terminated correctly
        self.assertIn(proc.wait(60), (-15, 0)) 
开发者ID:apache,项目名称:airflow,代码行数:21,代码来源:test_webserver_command.py

示例3: pyrun

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def pyrun(src, **kwds):
    """Run python 'src' code string in a separate interpreter.
    Returns a subprocess.Popen instance and the test file where the source
    code was written.
    """
    kwds.setdefault("stdout", None)
    kwds.setdefault("stderr", None)
    srcfile = get_testfn()
    try:
        with open(srcfile, 'wt') as f:
            f.write(src)
        subp = spawn_testproc([PYTHON_EXE, f.name], **kwds)
        wait_for_pid(subp.pid)
        return (subp, srcfile)
    except Exception:
        safe_rmpath(srcfile)
        raise 
开发者ID:giampaolo,项目名称:psutil,代码行数:19,代码来源:__init__.py

示例4: sh

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def sh(cmd, **kwds):
    """run cmd in a subprocess and return its output.
    raises RuntimeError on error.
    """
    shell = True if isinstance(cmd, (str, unicode)) else False
    # Prevents subprocess to open error dialogs in case of error.
    flags = 0x8000000 if WINDOWS and shell else 0
    kwds.setdefault("shell", shell)
    kwds.setdefault("stdout", subprocess.PIPE)
    kwds.setdefault("stderr", subprocess.PIPE)
    kwds.setdefault("universal_newlines", True)
    kwds.setdefault("creationflags", flags)
    p = subprocess.Popen(cmd, **kwds)
    _subprocesses_started.add(p)
    if PY3:
        stdout, stderr = p.communicate(timeout=GLOBAL_TIMEOUT)
    else:
        stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise RuntimeError(stderr)
    if stderr:
        warn(stderr)
    if stdout.endswith('\n'):
        stdout = stdout[:-1]
    return stdout 
开发者ID:giampaolo,项目名称:psutil,代码行数:27,代码来源:__init__.py

示例5: test_cli_webserver_foreground_with_pid

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def test_cli_webserver_foreground_with_pid(self):
        with tempfile.TemporaryDirectory(prefix='tmp-pid') as tmpdir:
            pidfile = "{}/pidfile".format(tmpdir)
            with mock.patch.dict(
                "os.environ",
                AIRFLOW__CORE__DAGS_FOLDER="/dev/null",
                AIRFLOW__CORE__LOAD_EXAMPLES="False",
                AIRFLOW__WEBSERVER__WORKERS="1"
            ):
                proc = subprocess.Popen(["airflow", "webserver", "--pid", pidfile])
                self.assertEqual(None, proc.poll())

            # Check the file specified by --pid option exists
            self._wait_pidfile(pidfile)

            # Terminate webserver
            proc.terminate()
            self.assertEqual(0, proc.wait(60)) 
开发者ID:apache,项目名称:airflow,代码行数:20,代码来源:test_webserver_command.py

示例6: start

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def start(self):
        if sys.platform == 'win32':
            args = [os.path.join(self.working_dir, 'run.bat')]
            # things break otherwise
            env = dict(os.environ)
        else:
            args = ['sh', os.path.join(self.working_dir, 'run.sh')]
            # Path needs to be passed through, otherwise some compilers (e.g gcc) can get confused and not find things
            env = {'PATH': os.environ['PATH']}

        env['PLAYER_KEY'] = str(self.player_key)
        env['RUST_BACKTRACE'] = '1'
        env['BC_PLATFORM'] = self._detect_platform()

        if isinstance(self.socket_file, tuple):
            # tcp port
            env['TCP_PORT'] = str(self.socket_file[1])
        else:
            env['SOCKET_FILE'] = self.socket_file

        cwd = self.working_dir
        self.process = psutil.Popen(args, env=env, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) 
开发者ID:battlecode,项目名称:bc18-scaffold,代码行数:24,代码来源:player_plain.py

示例7: _attend_process

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def _attend_process(self, proc, sleeptime):
        """
        Waits on a process for a given time to see if it finishes, returns True
        if it's still running after the given time or False as soon as it 
        returns.

        :param psutil.Popen proc: Process object opened by psutil.Popen()
        :param float sleeptime: Time to wait
        :return bool: True if process is still running; otherwise false
        """
        # print("attend:{}".format(proc.pid))
        try:
            proc.wait(timeout=sleeptime)
        except psutil.TimeoutExpired:
            return True
        return False 
开发者ID:databio,项目名称:pypiper,代码行数:18,代码来源:manager.py

示例8: connect

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def connect(cls, datadir, jarfile):
        # Check for running server instances
        jar = os.path.split(jarfile)[-1]
        for p in psutil.process_iter(attrs = ["name", "cmdline"]):
            if (p.info["name"] == "java" and
                any(x.endswith(jar) for x in p.info["cmdline"])):
                return

        # Start server
        cmdline = ["java", "-Xmx2G", "-XX:+UseG1GC", "-jar",
                   jarfile, str(cls.rpc_port), datadir]
        cls.rpc_server_proc = psutil.Popen(cmdline)

        atexit.register(RemoteServer.disconnect)
        with grpc.insecure_channel(cls.rpc_uri) as chan:
            grpc.channel_ready_future(chan).result(timeout = 60.0) 
开发者ID:ut-astria,项目名称:orbdetpy,代码行数:18,代码来源:server.py

示例9: __call__

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def __call__(self, request, s):
        files = [{NAME: file.filename, STREAM: file.stream} for file in request.files.getlist('files')]
        items = request.form.getlist('kit')
        force = parse_bool(request.form.get('force'))
        # we do this in two stages
        # first, immediate saving of files while web browser waiting for response
        upload_files(Record(log), self.__data, files=files, nfiles=len(files), items=items)
        # second, start rest of ingest process in background
        cmd = f'{command_root()} {mm(VERBOSITY)} 0 {mm(BASE)} {self.__data.base} {mm(LOG)} {WEB}-{READ}.log'
        if global_dev(): cmd += f' {mm(DEV)}'
        cmd += f' {READ}'
        if force: cmd += f' {mm(FORCE)}'
        log.info(f'Starting {cmd}')
        ps.Popen(args=cmd, shell=True)
        # wait so that the progress has time to kick in
        self.__data.sys.wait_for_progress(READ) 
开发者ID:andrewcooke,项目名称:choochoo,代码行数:18,代码来源:upload.py

示例10: run_github_page_locally

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def run_github_page_locally(github_page_dirpath):
  run_github_page_locally_process = psutil.Popen(
    [os.path.join(MODULE_DIRPATH, "run_github_page_locally.sh"), "--release"])
  
  page_config_filepath = os.path.join(github_page_dirpath, PAGE_CONFIG_FILENAME)
  
  with io.open(page_config_filepath, "r", encoding=FILE_ENCODING) as page_config_file:
    page_config = yaml.load(page_config_file.read())
  
  page_ready = False
  
  while not page_ready:
    try:
      requests.get(
        "http://{}:{}{}/".format(
          JEKYLL_SERVER_LOCALHOST_IP, JEKYLL_SERVER_PORT, page_config["baseurl"]))
    except requests.ConnectionError:
      pass
    else:
      page_ready = True
  
  for child in run_github_page_locally_process.children(recursive=True):
    child.kill()
  
  run_github_page_locally_process.kill() 
开发者ID:khalim19,项目名称:gimp-plugin-export-layers,代码行数:27,代码来源:create_user_docs.py

示例11: execute

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def execute(cmd, stderr_to_stdout=False, stdin=None):
    """Execute a command in the shell and return a tuple (rc, stdout, stderr)"""
    if stderr_to_stdout:
        stderr = STDOUT
    else:
        stderr = PIPE

    if stdin is None:
        _stdin = None
    else:
        _stdin = PIPE

    p = Popen(cmd, close_fds=True, stdin=_stdin, stdout=PIPE, stderr=stderr, preexec_fn=os.setsid)
    stdout, stderr = p.communicate(input=stdin)

    return p.returncode, stdout, stderr 
开发者ID:erigones,项目名称:esdc-ce,代码行数:18,代码来源:cmd.py

示例12: _execute

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def _execute(cmd, stdin=None, stderr_to_stdout=False):
    """Run command and return output"""
    logger.log(IMPORTANT, 'Running command (panel): %s', cmd)

    if stderr_to_stdout:
        stderr = STDOUT
    else:
        stderr = PIPE

    proc = Popen(cmd, bufsize=0, close_fds=True, stdout=PIPE, stderr=stderr, stdin=PIPE)
    stdout, stderr = proc.communicate(input=stdin)

    return {
        'returncode': proc.returncode,
        'stdout': stdout,
        'stderr': stderr,
    }


# noinspection PyUnusedLocal 
开发者ID:erigones,项目名称:esdc-ce,代码行数:22,代码来源:handlers.py

示例13: test_kill_terminate

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def test_kill_terminate(self):
        # subprocess.Popen()'s terminate(), kill() and send_signal() do
        # not raise exception after the process is gone. psutil.Popen
        # diverges from that.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.terminate()
            proc.wait()
            self.assertRaises(psutil.NoSuchProcess, proc.terminate)
            self.assertRaises(psutil.NoSuchProcess, proc.kill)
            self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                              signal.SIGTERM)
            if WINDOWS and sys.version_info >= (2, 7):
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_C_EVENT)
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_BREAK_EVENT) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:20,代码来源:test_process.py

示例14: __init__

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def __init__(self, cmd: str, proc: psutil.Popen, uri: str) -> None:
        msg = (
            "Able to launch RPC client, but unable to connect."
            f"\n\nCommand: {cmd}\nURI: {uri}\nExit Code: {proc.poll()}"
        )
        if sys.platform != "win32":
            out = proc.stdout.read().decode().strip() or "  (Empty)"
            err = proc.stderr.read().decode().strip() or "  (Empty)"
            msg = f"{msg}\n\nStdout:\n{out}\n\nStderr:\n{err}"
        super().__init__(msg) 
开发者ID:eth-brownie,项目名称:brownie,代码行数:12,代码来源:exceptions.py

示例15: is_active

# 需要导入模块: import psutil [as 别名]
# 或者: from psutil import Popen [as 别名]
def is_active(self) -> bool:
        """Returns True if Rpc client is currently active."""
        if not self._rpc:
            return False
        if type(self._rpc) is psutil.Popen:
            self._rpc.poll()
        return self._rpc.is_running() 
开发者ID:eth-brownie,项目名称:brownie,代码行数:9,代码来源:rpc.py


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