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


Python subprocess.check_output方法代码示例

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


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

示例1: run_command

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def run_command(cmd, **kwargs):
    """Run a command and return the output.

    .. versionadded:: 1.31

    A thin wrapper around :func:`subprocess.check_output` that ensures
    all arguments are encoded to UTF-8 first.

    Args:
        cmd (list): Command arguments to pass to ``check_output``.
        **kwargs: Keyword arguments to pass to ``check_output``.

    Returns:
        str: Output returned by ``check_output``.
    """
    cmd = [utf8ify(s) for s in cmd]
    return subprocess.check_output(cmd, **kwargs) 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:19,代码来源:util.py

示例2: load_addresses

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def load_addresses():
    """
    Separate function to avoid announce when loading addresses from keystore.
    """
    global ADDRESSES
    try:
        response = subprocess.check_output(["hmy", "keys", "list"], env=ENVIRONMENT).decode()
    except subprocess.CalledProcessError as err:
        raise RuntimeError(f"Could not list keys.\n"
                           f"\tGot exit code {err.returncode}. Msg: {err.output}") from err

    lines = response.split("\n")
    if "NAME" not in lines[0] or "ADDRESS" not in lines[0]:
        raise RuntimeError(f"Name or Address not found on first line if key list.")

    for line in lines[1:]:
        if not line:
            continue
        try:
            name, address = line.split("\t")
        except ValueError:
            raise RuntimeError(f"Unexpected key list format.")
        ADDRESSES[name.strip()] = address 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:25,代码来源:testHmy.py

示例3: saveTimingInfo

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def saveTimingInfo(summary):
    timingsPath = "test_timings.csv"
    git_version = subprocess.check_output(["git", "describe"]).strip()
    
    new_row = summary[["timing"]].T
    new_row["date"] = [datetime.datetime.now()]
    new_row["version"] = git_version


    if os.path.exists(timingsPath):
        timings = pandas.read_csv(timingsPath, index_col=0)
        timings = pandas.concat([timings, new_row])
    else:
        timings = new_row

    timings.to_csv(timingsPath)

    print(timings) 
开发者ID:svviz,项目名称:svviz,代码行数:20,代码来源:runTests.py

示例4: _call_gti

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def _call_gti(self, command, num_values):
        try:
            response_json = check_output(command, shell=True)
            result_dict = json.loads(response_json[0:len(response_json) - 1])
            responses = result_dict['a']
            return responses

        except CalledProcessError as e:
            self._logger.error("Error calling McAfee GTI client in gti module: " + e.output)
            error_resp = [{self.REP_KEY: self.DEFAULT_REP}] * num_values
            return error_resp

        except ValueError as e:
            self._logger.error("Error reading JSON response in gti module: " + e.message)
            error_resp = [{self.REP_KEY: self.DEFAULT_REP}] * num_values
            return error_resp 
开发者ID:apache,项目名称:incubator-spot,代码行数:18,代码来源:gti.py

示例5: _get_terminal_size_tput

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def _get_terminal_size_tput(self):
        # get terminal width
        # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
        try:
            cols = int(
                subprocess.check_output(
                    shlex.split("tput cols"), stderr=subprocess.STDOUT
                )
            )
            rows = int(
                subprocess.check_output(
                    shlex.split("tput lines"), stderr=subprocess.STDOUT
                )
            )

            return (cols, rows)
        except:
            pass 
开发者ID:sdispater,项目名称:clikit,代码行数:20,代码来源:terminal.py

示例6: context_function_signatures

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def context_function_signatures(context, vcc_path=VCC_PATH):
    ctx_info = subprocess.check_output([vcc_path, '-X', context])
    ctx_info = ctx_info.decode('ascii')

    sigs = []
    for s in re.findall('(\w+(\[\])?) (\w+)\((.*)\)', ctx_info):
        sig_str  = '%s %s(%s)' % (s[0], s[2], s[3])
        if s[3] == 'void':
            hint_str = ''
        else:
            hint_str = '%s\n(%s)' % (s[0], s[3].rstrip().lstrip().rstrip(';'))
        args = [x.strip() for x in s[3].split(';')]
        sigs.append({'returns':s[0], 'name':s[2], 'ctx':context, 'args':args, 'str':sig_str,
                     'hint':hint_str})

    return sigs 
开发者ID:WhileRomeBurns,项目名称:VEX_Syntax,代码行数:18,代码来源:vcc_utils.py

示例7: manage

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def manage():
    def call(*args, **kwargs):
        ignore_errors = kwargs.pop("ignore_errors", False)
        assert not kwargs
        cmd = [
            sys.executable,
            os.path.join(os.path.dirname(__file__), "testprj", "manage.py"),
        ] + list(args)
        try:
            return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            if not ignore_errors:
                raise
            return e.output

    return call 
开发者ID:GaretJax,项目名称:django-click,代码行数:18,代码来源:conftest.py

示例8: _verify_docker_image_size

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def _verify_docker_image_size(self, image_name):
    """Verifies size of Docker image.

    Args:
      image_name: name of the Docker image.

    Returns:
      True if image size is withing the limits, False otherwise.
    """
    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size) if PY3 else long(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:23,代码来源:validate_submission_lib.py

示例9: run

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def run(self):
    """Runs validation of all submissions."""
    cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')]
    try:
      files_list = subprocess.check_output(cmd).split('\n')
    except subprocess.CalledProcessError:
      logging.error('Can''t read source directory')
    all_submissions = [
        s for s in files_list
        if s.endswith('.zip') or s.endswith('.tar') or s.endswith('.tar.gz')
    ]
    for submission_path in all_submissions:
      self.validate_and_copy_one_submission(submission_path)
    self.stats.log_stats()
    self.save_id_to_path_mapping()
    if self.containers_file:
      with open(self.containers_file, 'w') as f:
        f.write('\n'.join(sorted(self.list_of_containers))) 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:20,代码来源:validate_and_copy_submissions.py

示例10: _verify_docker_image_size

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def _verify_docker_image_size(self, image_name):
    """Verifies size of Docker image.

    Args:
      image_name: name of the Docker image.

    Returns:
      True if image size is within the limits, False otherwise.
    """
    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size) if PY3 else long(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:23,代码来源:validate_submission_lib.py

示例11: list_gpus

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def list_gpus():
    """Return a list of GPUs

    Returns
    -------
    list of int:
        If there are n GPUs, then return a list [0,1,...,n-1]. Otherwise returns
        [].
    """
    re = ''
    nvidia_smi = ['nvidia-smi', '/usr/bin/nvidia-smi', '/usr/local/nvidia/bin/nvidia-smi']
    for cmd in nvidia_smi:
        try:
            re = subprocess.check_output([cmd, "-L"], universal_newlines=True)
        except OSError:
            pass
    return range(len([i for i in re.split('\n') if 'GPU' in i])) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:19,代码来源:test_utils.py

示例12: delete_local_docker_cache

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def delete_local_docker_cache(docker_tag):
    """
    Delete the local docker cache for the entire docker image chain
    :param docker_tag: Docker tag
    :return: None
    """
    history_cmd = ['docker', 'history', '-q', docker_tag]

    try:
        image_ids_b = subprocess.check_output(history_cmd)
        image_ids_str = image_ids_b.decode('utf-8').strip()
        layer_ids = [id.strip() for id in image_ids_str.split('\n') if id != '<missing>']

        delete_cmd = ['docker', 'image', 'rm', '--force']
        delete_cmd.extend(layer_ids)
        subprocess.check_call(delete_cmd)
    except subprocess.CalledProcessError as error:
        # Could be caused by the image not being present
        logging.debug('Error during local cache deletion %s', error) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:21,代码来源:docker_cache.py

示例13: check_project

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def check_project(project_name):
    if 'token' in if_config_vars and len(if_config_vars['token']) != 0:
        logger.debug(project_name)
        try:
            # check for existing project
            check_url = urlparse.urljoin(if_config_vars['if_url'], '/api/v1/getprojectstatus')
            output_check_project = subprocess.check_output('curl "' + check_url + '?userName=' + if_config_vars['user_name'] + '&token=' + if_config_vars['token'] + '&projectList=%5B%7B%22projectName%22%3A%22' + project_name + '%22%2C%22customerName%22%3A%22' + if_config_vars['user_name'] + '%22%2C%22projectType%22%3A%22CUSTOM%22%7D%5D&tzOffset=-14400000"', shell=True)
            # create project if no existing project
            if project_name not in output_check_project:
                logger.debug('creating project')
                create_url = urlparse.urljoin(if_config_vars['if_url'], '/api/v1/add-custom-project')
                output_create_project = subprocess.check_output('no_proxy= curl -d "userName=' + if_config_vars['user_name'] + '&token=' + if_config_vars['token'] + '&projectName=' + project_name + '&instanceType=PrivateCloud&projectCloudType=PrivateCloud&dataType=' + get_data_type_from_project_type() + '&samplingInterval=' + str(if_config_vars['sampling_interval'] / 60) +  '&samplingIntervalInSeconds=' + str(if_config_vars['sampling_interval']) + '&zone=&email=&access-key=&secrete-key=&insightAgentType=' + get_insight_agent_type_from_project_type() + '" -H "Content-Type: application/x-www-form-urlencoded" -X POST ' + create_url + '?tzOffset=-18000000', shell=True)
            # set project name to proposed name
            if_config_vars['project_name'] = project_name
            # try to add new project to system
            if 'system_name' in if_config_vars and len(if_config_vars['system_name']) != 0:
                system_url = urlparse.urljoin(if_config_vars['if_url'], '/api/v1/projects/update')
                output_update_project = subprocess.check_output('no_proxy= curl -d "userName=' + if_config_vars['user_name'] + '&token=' + if_config_vars['token'] + '&operation=updateprojsettings&projectName=' + project_name + '&systemName=' + if_config_vars['system_name'] + '" -H "Content-Type: application/x-www-form-urlencoded" -X POST ' + system_url + '?tzOffset=-18000000', shell=True)
        except subprocess.CalledProcessError as e:
            logger.error('Unable to create project for ' + project_name + '. Data will be sent to ' + if_config_vars['project_name']) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:22,代码来源:getlogs_servicenow.py

示例14: test_and_load_keystore_directory

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def test_and_load_keystore_directory():
    """
    CRITICAL TEST
    """
    global KEYSTORE_PATH
    try:
        response = subprocess.check_output(["hmy", "keys", "location"], env=ENVIRONMENT).decode().strip()
    except subprocess.CalledProcessError as err:
        log(f"Failed: Could not get keystore path.\n"
            f"\tGot exit code {err.returncode}. Msg: {err.output}")
        return False
    if not os.path.exists(response):
        log(f"Failed: '{response}' is not a valid path")
        return False
    KEYSTORE_PATH = response
    log("Passed", error=False)
    return True 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:19,代码来源:testHmy.py

示例15: detect_file_manager

# 需要导入模块: import subprocess [as 别名]
# 或者: from subprocess import check_output [as 别名]
def detect_file_manager(self):
        try:
            fm = subprocess.check_output(['xdg-mime',
                                          'query',
                                          'default',
                                          'inode/directory'])
            detected_fm = fm.decode('utf-8').strip().lower()
            known_fm = ['dolphin',
                        'nemo',
                        'nautilus',
                        'doublecmd',
                        'thunar',
                        'pcmanfm-qt',
                        'pcmanfm',
                        'spacefm']
            for x in known_fm:
                if x in detected_fm:
                    print('autodetected file manager: ' + x)
                    return x
            return 'xdg-open'

        except Exception as err:
            print(err)
            return 'xdg-open' 
开发者ID:DoTheEvo,项目名称:ANGRYsearch,代码行数:26,代码来源:angrysearch.py


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