當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。