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


Python subprocess.SubprocessError方法代码示例

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


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

示例1: test_create_scaffold

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def test_create_scaffold(self):
        project_name = "projectABC"
        create_scaffold(project_name)
        self.assertTrue(os.path.isdir(os.path.join(project_name, "har")))
        self.assertTrue(os.path.isdir(os.path.join(project_name, "testcases")))
        self.assertTrue(os.path.isdir(os.path.join(project_name, "reports")))
        self.assertTrue(os.path.isfile(os.path.join(project_name, "debugtalk.py")))
        self.assertTrue(os.path.isfile(os.path.join(project_name, ".env")))

        # run demo testcases
        try:
            subprocess.check_call(["hrun", project_name])
        except subprocess.SubprocessError:
            raise
        finally:
            shutil.rmtree(project_name) 
开发者ID:httprunner,项目名称:httprunner,代码行数:18,代码来源:scaffold_test.py

示例2: _fetch_lfs_files

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _fetch_lfs_files(self, repo_path, paths):
        """Fetch and checkout paths that are tracked by Git LFS."""
        repo_path = str(repo_path)
        try:
            output = run(('git', 'lfs', 'ls-files', '--name-only'),
                         stdout=PIPE,
                         cwd=repo_path,
                         universal_newlines=True)
        except SubprocessError:
            return

        lfs_files = set(output.stdout.split('\n'))
        files = lfs_files & paths
        if not files:
            return

        try:
            for path in files:
                run(['git', 'lfs', 'pull', '--include', path], cwd=repo_path)
        except KeyboardInterrupt:
            raise
        except SubprocessError:
            pass 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:25,代码来源:datasets.py

示例3: test_surrogates_error_message

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def test_surrogates_error_message(self):
        def prepare():
            raise ValueError("surrogate:\uDCff")

        try:
            subprocess.call(
                [sys.executable, "-c", "pass"],
                preexec_fn=prepare)
        except ValueError as err:
            # Pure Python implementations keeps the message
            self.assertIsNone(subprocess._posixsubprocess)
            self.assertEqual(str(err), "surrogate:\uDCff")
        except subprocess.SubprocessError as err:
            # _posixsubprocess uses a default message
            self.assertIsNotNone(subprocess._posixsubprocess)
            self.assertEqual(str(err), "Exception occurred in preexec_fn.")
        else:
            self.fail("Expected ValueError or subprocess.SubprocessError") 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_subprocess.py

示例4: install_package

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def install_package(package, upgrade=True,
                    target=None):
    """Install a package on PyPi. Accepts pip compatible package strings.

    Return boolean if install successful.
    """
    # Not using 'import pip; pip.main([])' because it breaks the logger
    with INSTALL_LOCK:
        if check_package_exists(package, target):
            return True

        _LOGGER.info('Attempting install of %s', package)
        args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
        if upgrade:
            args.append('--upgrade')
        if target:
            args += ['--target', os.path.abspath(target)]

        try:
            return subprocess.call(args) == 0
        except subprocess.SubprocessError:
            _LOGGER.exception('Unable to install pacakge %s', package)
            return False 
开发者ID:django-leonardo,项目名称:django-leonardo,代码行数:25,代码来源:package.py

示例5: sysexec

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def sysexec(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    response = None
    if pld.args:
        try:
            process = subprocess.run(pld.args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
            await pld.msg.add_reaction('✔')
            response = from_output(process.stdout)
        except (OSError, subprocess.SubprocessError) as e:
            cmd.log.error(e)
            await pld.msg.add_reaction('❗')
    else:
        response = 'No input.'
    if response:
        await pld.msg.channel.send(response) 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:22,代码来源:sysexec.py

示例6: install_requirements

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def install_requirements():
    """
    Tries to install the pip requirements
    if startup fails due to a missing module.
    :return:
    """
    global modules_installed
    if not modules_installed:
        pip_cmd = ['pip', 'install', '-Ur', 'requirements.txt']
        print('Missing required modules, trying to install them...')
        try:
            subprocess.run(pip_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
            modules_installed = True
        except (OSError, subprocess.SubprocessError):
            print('Requirement update failed!')
            exit(errno.EINVAL)
    else:
        print('Trying to install missing requirements did not work, please contact Sigma\'s developers.')
        exit(errno.EINVAL) 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:21,代码来源:run.py

示例7: _syscall

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _syscall(func):
    def wrapper(package=None):
        try:
            if package:
                return func(package)
            return func()
        except subprocess.SubprocessError as exp:
            cmd = getattr(exp, "cmd", None)
            if cmd:
                msg = 'Error calling system command "{0}"'.format(
                    " ".join(cmd)
                )
            if package:
                msg = '{0} for package "{1}"'.format(msg, package)
            raise RuntimeError(msg)

    return wrapper 
开发者ID:open-telemetry,项目名称:opentelemetry-python,代码行数:19,代码来源:bootstrap.py

示例8: _get_scm_timestamp_for

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _get_scm_timestamp_for(commitish, *, scm=None):
    """Retrieve the tag date from SCM."""
    if scm is None:
        scm = 'git'

    try:
        ts = subprocess.check_output(
            _SCM_COMMANDS[scm] + (commitish, ),
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()
    except subprocess.SubprocessError:
        raise ValueError(
            f'There is no `{commitish}` in {scm.title()}',
        ) from None

    return dateutil.parser.parse(ts) 
开发者ID:cherrypy,项目名称:cheroot,代码行数:19,代码来源:scm_tag_titles_ext.py

示例9: notarization_info

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def notarization_info(uuid: str, username: str, password: str) -> dict:
    completed_process = run(
        [
            altool,
            "--notarization-info",
            uuid,
            f"--username={username}",
            f"--password={password}",
        ],
        capture_output=True,
        text=True,
    )
    stdout = completed_process.stdout.strip()
    stderr = completed_process.stderr.strip()
    if completed_process.returncode or stderr:
        raise SubprocessError(stderr)
    results = {}
    for line in stdout.split("\n"):
        if line:
            split = line.split(":")
            key = split[0].strip()
            value = ":".join(split[1:]).strip()
            if key and value:
                results[key] = value
    return results 
开发者ID:gridsync,项目名称:gridsync,代码行数:27,代码来源:notarize.py

示例10: default_gateway_ip

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def default_gateway_ip():
    """
    Returns gateway IP address of the host that testcontainer process is
    running on

    https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L27
    """
    cmd = ["sh", "-c", "ip route|awk '/default/ { print $3 }'"]
    try:
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        ip_address = process.communicate()[0]
        if ip_address and process.returncode == 0:
            return ip_address.decode('utf-8').strip().strip('\n')
    except subprocess.SubprocessError:
        return None 
开发者ID:testcontainers,项目名称:testcontainers-python,代码行数:18,代码来源:utils.py

示例11: _spawn_process

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _spawn_process(self, args, **subprocess_kwargs):
        process = None
        try:
            process = subprocess.Popen(args, **subprocess_kwargs)
        except FileNotFoundError:
            executable = args.partition(' ')[0] if isinstance(args, str) else args[0]
            raise ClientException(executable + ' was not found.') from None
        except subprocess.SubprocessError as exc:
            raise ClientException('Popen failed: {0.__class__.__name__}: {0}'.format(exc)) from exc
        else:
            return process 
开发者ID:Rapptz,项目名称:discord.py,代码行数:13,代码来源:player.py

示例12: dmesg

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def dmesg(self):
        # reading last 20 lines of the kernel's dmesg buffer... (requires root privilege)
        try:
            result = subprocess.check_output(["dmesg", "--nopager", "--level", "info"])
            return result.decode().splitlines()[-20:]
        except subprocess.SubprocessError as x:
            raise OSError("couldn't run the dmesg command in the server: " + str(x)) 
开发者ID:irmen,项目名称:Pyro5,代码行数:9,代码来源:elevated_server.py

示例13: install_dependenies

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def install_dependenies(deps: List[str]):
    resp = {"code": 0, "message": "success", "result": {}}
    for dep in deps:
        try:
            p = subprocess.run(["pip", "install", dep])
            assert p.returncode == 0
            resp["result"][dep] = True
        except (AssertionError, subprocess.SubprocessError):
            resp["result"][dep] = False
            resp["code"] = 1
            resp["message"] = "fail"
            logger.error(f"failed to install dependency: {dep}")

    return resp 
开发者ID:httprunner,项目名称:httprunner,代码行数:16,代码来源:deps.py

示例14: _delete_ssh_key

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _delete_ssh_key(self) -> None:
        """
        Delete SSH key from `~/.ssh/known_hosts`.

        We can safely ignore the command's return code, because we just need to be sure that the key has been removed
        for non-existing server - we don't care about non-existing keys.
        """
        self.logger.info('Deleting SSH key of "%s" host.', self.public_ip)
        command = f'ssh-keygen -R {self.public_ip}'
        try:
            subprocess.Popen(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except subprocess.SubprocessError as e:
            self.logger.error('Failed to delete SSH key of "%s" host: %s', self.public_ip, e) 
开发者ID:open-craft,项目名称:opencraft,代码行数:15,代码来源:server.py

示例15: _get_file_size

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import SubprocessError [as 别名]
def _get_file_size(self, remote_client, path):
        # Try to get file size from Git LFS
        try:
            lfs_run = run(('git', 'lfs', 'ls-files', '--name-only', '--size'),
                          stdout=PIPE,
                          cwd=remote_client.path,
                          universal_newlines=True)
        except SubprocessError:
            pass
        else:
            lfs_output = lfs_run.stdout.split('\n')
            # Example line format: relative/path/to/file (7.9 MB)
            pattern = re.compile(r'.*\((.*)\)')
            for line in lfs_output:
                if path not in line:
                    continue
                match = pattern.search(line)
                if not match:
                    continue
                size_info = match.groups()[0].split()
                if len(size_info) != 2:
                    continue
                try:
                    size = float(size_info[0])
                except ValueError:
                    continue
                unit = size_info[1].strip().lower()
                conversions = {'b': 1, 'kb': 1e3, 'mb': 1e6, 'gb': 1e9}
                multiplier = conversions.get(unit, None)
                if multiplier is None:
                    continue
                return size * multiplier

        # Return size of the file on disk
        full_path = remote_client.path / path
        return os.path.getsize(full_path) 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:38,代码来源:renku.py


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