当前位置: 首页>>代码示例>>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;未经允许,请勿转载。