當前位置: 首頁>>代碼示例>>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: _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

示例4: 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

示例5: _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

示例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;未經允許,請勿轉載。