當前位置: 首頁>>代碼示例>>Python>>正文


Python subprocess.CompletedProcess方法代碼示例

本文整理匯總了Python中subprocess.CompletedProcess方法的典型用法代碼示例。如果您正苦於以下問題:Python subprocess.CompletedProcess方法的具體用法?Python subprocess.CompletedProcess怎麽用?Python subprocess.CompletedProcess使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在subprocess的用法示例。


在下文中一共展示了subprocess.CompletedProcess方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _run

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def _run(*args, env=None, check=False, timeout=None):
    encoded_args = [a.encode('utf-8') for a in args] if sys.platform != 'win32' else args
    with subprocess.Popen(encoded_args, env=env, stdout=PIPE, stderr=PIPE) as process:
        try:
            stdout, stderr = process.communicate(input, timeout=timeout)
        except TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise TimeoutExpired(
                process.args, timeout, output=stdout, stderr=stderr,
            )
        except Exception:
            process.kill()
            process.wait()
            raise
        retcode = process.poll()
        if check and retcode:
            raise subprocess.CalledProcessError(
                retcode, process.args, output=stdout, stderr=stderr,
            )
        return subprocess.CompletedProcess(process.args, retcode, stdout, stderr) 
開發者ID:smarkets,項目名稱:marge-bot,代碼行數:23,代碼來源:git.py

示例2: mulled_upload

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def mulled_upload(image: str, quay_target: str) -> sp.CompletedProcess:
    """
    Upload the build Docker images to quay.io with ``mulled-build push``.

    Calls ``mulled-build push <image> -n <quay_target>``

    Args:
      image: name of image to push
      quary_target: name of image on quay
    """
    cmd = ['mulled-build', 'push', image, '-n', quay_target]
    mask = []
    if os.environ.get('QUAY_OAUTH_TOKEN', False):
        token = os.environ['QUAY_OAUTH_TOKEN']
        cmd.extend(['--oauth-token', token])
        mask = [token]
    return utils.run(cmd, mask=mask) 
開發者ID:bioconda,項目名稱:bioconda-utils,代碼行數:19,代碼來源:upload.py

示例3: _app_deploy_with_retry

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def _app_deploy_with_retry(gcloud_path: str, project: str,
                               app_yaml_path: str, env_vars: Dict[str, Any]
                              ) -> subprocess.CompletedProcess:
        """Run 'gcloud app deploy' with retries.

        Args:
            gcloud_path: The path of your gcloud cli tool.
            project: GCP project id.
            app_yaml_path: Absolute path of your app.yaml.
            env_vars: A dictionary of the environment variables.

        Returns:
            The result of the subprocess run.
        """
        gcloud_result = subprocess.run(
            [gcloud_path, '-q', project, 'app', 'deploy', app_yaml_path],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            env=env_vars)
        return gcloud_result 
開發者ID:GoogleCloudPlatform,項目名稱:django-cloud-deploy,代碼行數:23,代碼來源:_deploygae.py

示例4: _execute

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def _execute(
    file: str, args: Sequence[str], cwd: Optional[Union[Path, str]], env: dict
) -> CompletedProcess:

    proc = Popen(args, executable=file, cwd=cwd, env=env)

    while True:
        try:
            returncode = proc.wait()
        except KeyboardInterrupt:
            pass
        else:
            break

    if returncode != 0:
        raise CalledProcessError(
            returncode=returncode, cmd=" ".join(shlex.quote(arg) for arg in args),
        )

    return CompletedProcess(args=args, returncode=returncode) 
開發者ID:raymondbutcher,項目名稱:pretf,代碼行數:22,代碼來源:util.py

示例5: custom

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def custom(
    path: Union[PurePath, str], context: Optional[dict] = None
) -> CompletedProcess:
    """
    Calls the pretf_workflow() function from the specified Python file.
    This is useful for having a custom workflow that is used by multiple
    pretf.workflow.py files in different directories.

    """

    with import_file(path) as module:

        if not hasattr(module, "pretf_workflow"):
            raise log.bad(f"workflow: {path} does not have a 'pretf_workflow' function")

        # Call the pretf_workflow() function,
        # passing in "path" and "terraform" if required.
        result = call_pretf_function(func=module.pretf_workflow, context=context)  # type: ignore

    if isinstance(result, int):
        result = CompletedProcess(args=[str(path)], returncode=result)

    return result 
開發者ID:raymondbutcher,項目名稱:pretf,代碼行數:25,代碼來源:workflow.py

示例6: run_command

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def run_command(cmd, check=False, timeout=None, shell=False, log=True):
    try:
        proc = run_command_async(cmd, shell=shell, start_new_session=True,
                                 log=log)
        proc_stdout, proc_stderr = proc.communicate(timeout=timeout)
    except subprocess.TimeoutExpired as e:
        os.killpg(proc.pid, signal.SIGKILL)
        raise SpawnedProcessTimeout(e.cmd,
                                    proc.stdout.read(),
                                    proc.stderr.read(), timeout) from None

    completed = subprocess.CompletedProcess(args=shlex.split(cmd),
                                            returncode=proc.returncode,
                                            stdout=proc_stdout,
                                            stderr=proc_stderr)

    if check and proc.returncode != 0:
        raise SpawnedProcessError(completed.args,
                                  completed.stdout, completed.stderr,
                                  completed.returncode)

    return completed 
開發者ID:eth-cscs,項目名稱:reframe,代碼行數:24,代碼來源:os_ext.py

示例7: check

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def check(self):
        """
        Check if the process has exited, and if an error occured.

        Returns None if process hasn't exited, or a CompletedProcess
        object if it has exited without an error. If the process
        has exited with an error, raises a CalledProcessError.

        If process has exited, all available stdout and stderr
        are captured into the returned object or raised exception.
        """
        retcode = self.poll()

        if retcode is not None:
            stdout, stderr = self.communicate(timeout=0)
            completed = subprocess.CompletedProcess(
                args=self.args,
                returncode=retcode,
                stdout=stdout,
                stderr=stderr,
            )
            completed.check_returncode()
            return completed 
開發者ID:alpernebbi,項目名稱:git-annex-adapter,代碼行數:25,代碼來源:process.py

示例8: check_output

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def check_output(
    args: Sequence[str],
    *,
    cwd: str = None,
    env: Mapping[str, str] = None,
    shell: bool = False
) -> subprocess.CompletedProcess:
    """
    Get the output of an invoked command.

    :param args: args should be a sequence of program arguments
    :param cwd: the working directory for the subprocess
    :param env: a dictionary with environment variables
    :param shell: whether to use the shell as the program to execute
    :returns: The `stdout` output of the command
    :rtype: str
    """
    rc, stdout_data, stderr_data = await _async_check_call(
        args, subprocess.PIPE, subprocess.PIPE,
        cwd=cwd, env=env, shell=shell, use_pty=False)
    if rc:
        stderr_data = stderr_data.decode(errors='replace')
    assert not rc, \
        'Expected {args} to pass: {stderr_data}'.format_map(locals())
    return stdout_data 
開發者ID:colcon,項目名稱:colcon-core,代碼行數:27,代碼來源:subprocess.py

示例9: run_command

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def run_command(cmd: str,
                verbose: bool = False,
                env: dict={}) -> subprocess.CompletedProcess:
    """ Run a command in a subprocess.

    Args:
        verbose: Show the output.

    Raises:
        subprocess.CalledProcessError: The given cmd exits with a non-0 exit
                                       code.
    """
    stdout = None if verbose else subprocess.PIPE
    stderr = None if verbose else subprocess.STDOUT
    p = subprocess.run(
        args=shlex.split(cmd),
        stdout=stdout,
        stderr=stderr,
        encoding='utf-8',
        check=True,
        env=env,
    )
    return p 
開發者ID:dcos,項目名稱:dcos,代碼行數:25,代碼來源:dcos_etcdctl.py

示例10: execute

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def execute(
            self,
            args: str,
            user_master_endpoint: bool=True,
            use_v3: bool = False,
    ) -> subprocess.CompletedProcess:
        cmd = self.etcdctl_path
        endpoint = self.get_endpoint(self.scheme, user_master_endpoint)
        cmd = "{} --endpoints={}".format(cmd, endpoint)
        cmd = "{} --cacert={} --cert={} --key={}".format(
            cmd, self.ca_cert_file, self.cert_file, self.key_file)
        cmd = "{} {}".format(cmd, args)
        env = {} if not use_v3 else {"ETCDCTL_API": "3"}
        result = run_command(cmd, env=env)

        self.log_cmd_result(args, result)

        return result 
開發者ID:dcos,項目名稱:dcos,代碼行數:20,代碼來源:dcos_etcdctl.py

示例11: test_for_conflicting_process

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def test_for_conflicting_process(
    mocked_info, mocked_warning, mocked_error, return_code, expected_result
):
    """
    Test whether we can successfully detect conflicting processes.
    """
    # We mock the pgrep call itself, which means we _won't_ detect behavior
    # changes at that level.
    completed_process = subprocess.CompletedProcess(args=[], returncode=return_code)
    with mock.patch("subprocess.run", return_value=completed_process) as mocked_run:
        running_process = util.is_conflicting_process_running(["cowsay"])
        mocked_run.assert_called_once()
        if expected_result is True:
            assert running_process is True
            mocked_error.assert_called_once()
            error_string = mocked_error.call_args[0][0]
            assert re.search(CONFLICTING_PROCESS_REGEX, error_string) is not None
        else:
            assert running_process is False
            assert not mocked_error.called 
開發者ID:freedomofpress,項目名稱:securedrop-workstation,代碼行數:22,代碼來源:test_util.py

示例12: test__lvm_report_returns_specific_reports

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def test__lvm_report_returns_specific_reports(self, m_run):
        report_key = 'report-1'
        report_data = [{random_string(): random_string()}]
        extra_data1 = [list(range(0, 10))]
        extra_data2 = ""
        cmd_out = json.dumps({
            "report": [
                {report_key: report_data},
                {random_string(): extra_data1},
                {random_string(): extra_data2},
             ]
        })
        cp = subprocess.CompletedProcess(args=[random_string()], returncode=0,
                                         stdout=cmd_out.encode('utf-8'),
                                         stderr="")
        m_run.return_value = cp
        expected_result = report_data
        result = lvm._lvm_report(random_string(), report_key)
        self.assertEqual(expected_result, result) 
開發者ID:canonical,項目名稱:probert,代碼行數:21,代碼來源:test_lvm.py

示例13: test_create_mutation_and_run_trial

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def test_create_mutation_and_run_trial(
    returncode, expected_status, monkeypatch, binop_file, binop_Add_LocIdx
):
    """Mocked trial to ensure mutated cache files are removed after running."""
    genome = Genome(source_file=binop_file)

    mutation_op = ast.Mult

    tag = sys.implementation.cache_tag
    expected_cfile = binop_file.parent / "__pycache__" / ".".join([binop_file.stem, tag, "pyc"])

    def mock_subprocess_run(*args, **kwargs):
        return CompletedProcess(args="pytest", returncode=returncode)

    monkeypatch.setattr(subprocess, "run", mock_subprocess_run)

    trial = run.create_mutation_run_trial(
        genome=genome,
        target_idx=binop_Add_LocIdx,
        mutation_op=mutation_op,
        test_cmds=["pytest"],
        max_runtime=10,
    )

    # mutated cache files should be removed after trial run
    assert not expected_cfile.exists()
    assert trial.status == expected_status 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:29,代碼來源:test_run.py

示例14: test_clean_trial_exception

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def test_clean_trial_exception(binop_file, monkeypatch):
    """Ensure clean trial raises a BaselineTestException on non-zero returncode"""

    def mock_subprocess_run(*args, **kwargs):
        return CompletedProcess(args="pytest", returncode=1)

    monkeypatch.setattr(subprocess, "run", mock_subprocess_run)

    with pytest.raises(BaselineTestException):
        run.clean_trial(binop_file.parent, ["pytest"]) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:12,代碼來源:test_run.py

示例15: test_clean_trial_timedelta

# 需要導入模塊: import subprocess [as 別名]
# 或者: from subprocess import CompletedProcess [as 別名]
def test_clean_trial_timedelta(binop_file, monkeypatch):
    """Clean trial results in a timedelta object."""

    def mock_subprocess_run(*args, **kwargs):
        return CompletedProcess(args="pytest", returncode=0)

    monkeypatch.setattr(subprocess, "run", mock_subprocess_run)

    result = run.clean_trial(binop_file.parent, ["pytest"])
    assert isinstance(result, timedelta) 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:12,代碼來源:test_run.py


注:本文中的subprocess.CompletedProcess方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。