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


Python yaml.load方法代碼示例

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


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

示例1: load_config

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def load_config(logdir):
  """Load a configuration from the log directory.

  Args:
    logdir: The logging directory containing the configuration file.

  Raises:
    IOError: The logging directory does not contain a configuration file.

  Returns:
    Configuration object.
  """
  config_path = logdir and os.path.join(logdir, 'config.yaml')
  if not config_path:
    message = (
        'Cannot resume an existing run since the logging directory does not '
        'contain a configuration file.')
    raise IOError(message)
  print("config_path=",config_path)

  stream = open(config_path, 'r')
  config = yaml.load(stream)
  message = 'Resume run and write summaries and checkpoints to {}.'
  print(message.format(logdir))
  return config 
開發者ID:utra-robosoccer,項目名稱:soccer-matlab,代碼行數:27,代碼來源:utility.py

示例2: load_config

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def load_config(logdir):
  """Load a configuration from the log directory.

  Args:
    logdir: The logging directory containing the configuration file.

  Raises:
    IOError: The logging directory does not contain a configuration file.

  Returns:
    Configuration object.
  """
  config_path = logdir and os.path.join(logdir, 'config.yaml')
  if not config_path or not tf.gfile.Exists(config_path):
    message = (
        'Cannot resume an existing run since the logging directory does not '
        'contain a configuration file.')
    raise IOError(message)
  with tf.gfile.FastGFile(config_path, 'r') as file_:
    config = yaml.load(file_)
  message = 'Resume run and write summaries and checkpoints to {}.'
  tf.logging.info(message.format(config.logdir))
  return config 
開發者ID:utra-robosoccer,項目名稱:soccer-matlab,代碼行數:25,代碼來源:utility.py

示例3: load_config

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def load_config(logdir):
  """Load a configuration from the log directory.

  Args:
    logdir: The logging directory containing the configuration file.

  Raises:
    IOError: The logging directory does not contain a configuration file.

  Returns:
    Configuration object.
  """
  config_path = logdir and os.path.join(logdir, 'config.yaml')
  if not config_path or not tf.gfile.Exists(config_path):
    message = (
        'Cannot resume an existing run since the logging directory does not '
        'contain a configuration file.')
    raise IOError(message)
  with tf.gfile.FastGFile(config_path, 'r') as file_:
    config = yaml.load(file_, Loader=yaml.Loader)
  message = 'Resume run and write summaries and checkpoints to {}.'
  tf.logging.info(message.format(config.logdir))
  return config 
開發者ID:utra-robosoccer,項目名稱:soccer-matlab,代碼行數:25,代碼來源:utility.py

示例4: read_config

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def read_config(path='aetros.yml', logger=None, return_default=True):
    path = os.path.normpath(os.path.abspath(os.path.expanduser(path)))

    config = {}

    if os.path.exists(path):
        f = open(path, 'r')

        config = yaml.load(f, Loader=yaml.RoundTripLoader)
        if config is None:
            config = {}

        if 'storage_dir' in config:
            del config['storage_dir']

        if 'model' in config and config['model']:
            config['root'] = os.path.dirname(path)

        logger and logger.debug('Config loaded from ' + os.path.realpath(path))

    if return_default:
        return apply_config_defaults(config)

    return config 
開發者ID:aetros,項目名稱:aetros-cli,代碼行數:26,代碼來源:__init__.py

示例5: load_results_sixd17

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def load_results_sixd17(path):
    """
    Loads 6D object pose estimates from a file.

    :param path: Path to a file with poses.
    :return: List of the loaded poses.
    """
    with open(path, 'r') as f:
        res = yaml.load(f, Loader=yaml.CLoader)
        if not res['ests'] or res['ests'] == [{}]:
            res['ests'] = []
        else:
            for est in res['ests']:
                est['R'] = np.array(est['R']).reshape((3, 3))
                est['t'] = np.array(est['t']).reshape((3, 1))
                # change basestring to str for py3
                if isinstance(est['score'], str):
                    if 'nan' in est['score']:
                        est['score'] = 0.0
                    else:
                        raise ValueError('Bad type of score.')
    return res 
開發者ID:meiqua,項目名稱:patch_linemod,代碼行數:24,代碼來源:inout.py

示例6: load_results_sixd17

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def load_results_sixd17(path):
    """
    Loads 6D object pose estimates from a file.

    :param path: Path to a file with poses.
    :return: List of the loaded poses.
    """
    with open(path, 'r') as f:
        res = yaml.load(f, Loader=yaml.CLoader)
        if not res['ests'] or res['ests'] == [{}]:
            res['ests'] = []
        else:
            for est in res['ests']:
                est['R'] = np.array(est['R']).reshape((3, 3))
                est['t'] = np.array(est['t']).reshape((3, 1))
                if isinstance(est['score'], basestring):
                    if 'nan' in est['score']:
                        est['score'] = 0.0
                    else:
                        raise ValueError('Bad type of score.')
    return res 
開發者ID:thodan,項目名稱:sixd_toolkit,代碼行數:23,代碼來源:inout.py

示例7: __init__

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def __init__(self,
                 filename=None,
                 content=None,
                 content_type='yaml',
                 separator='.',
                 backup_ext=None,
                 backup=False):
        self.content = content
        self._separator = separator
        self.filename = filename
        self.__yaml_dict = content
        self.content_type = content_type
        self.backup = backup
        if backup_ext is None:
            self.backup_ext = ".{}".format(time.strftime("%Y%m%dT%H%M%S"))
        else:
            self.backup_ext = backup_ext

        self.load(content_type=self.content_type)
        if self.__yaml_dict is None:
            self.__yaml_dict = {} 
開發者ID:RedHatOfficial,項目名稱:ansible-redhat_openshift_utils,代碼行數:23,代碼來源:oc_obj.py

示例8: create

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def create(self, path, value):
        ''' create a yaml file '''
        if not self.file_exists():
            # deepcopy didn't work
            # Try to use ruamel.yaml and fallback to pyyaml
            try:
                tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
                                                          default_flow_style=False),
                                     yaml.RoundTripLoader)
            except AttributeError:
                tmp_copy = copy.deepcopy(self.yaml_dict)

            # set the format attributes if available
            try:
                tmp_copy.fa.set_block_style()
            except AttributeError:
                pass

            result = Yedit.add_entry(tmp_copy, path, value, self.separator)
            if result is not None:
                self.yaml_dict = tmp_copy
                return (True, self.yaml_dict)

        return (False, self.yaml_dict) 
開發者ID:RedHatOfficial,項目名稱:ansible-redhat_openshift_utils,代碼行數:26,代碼來源:oc_obj.py

示例9: test_raises_errors_when_missing_heading

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def test_raises_errors_when_missing_heading(self, mock_helm, mock_yaml):
        course_yml = {
            'namespace': 'fake',
            'charts': {
                'fake-chart': {
                    'chart': 'none',
                    'version': 'none',
                    'repository': 'none',
                }
            }
        }

        mock_yaml.load.side_effect = [course_yml]
        helm_args = ['provided args']
        helm_instance = mock_helm(helm_args)
        helm_instance.client_version = '0.0.0'

        instance = reckoner.course.Course(None)
        with self.assertRaises(exception.NoChartsToInstall):
            instance.plot(['a-chart-that-is-not-defined']) 
開發者ID:FairwindsOps,項目名稱:reckoner,代碼行數:22,代碼來源:test_reckoner.py

示例10: test_passes_if_any_charts_exist

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def test_passes_if_any_charts_exist(self, mock_helm, mock_yaml):
        course_yml = {
            'namespace': 'fake',
            'charts': {
                'fake-chart': {
                    'chart': 'none',
                    'version': 'none',
                    'repository': 'none',
                }
            }
        }

        mock_yaml.load.side_effect = [course_yml]
        # this is not okay I assume, I just added args
        helm_args = ['provided args']
        helm_instance = mock_helm(helm_args)
        helm_instance.client_version = '0.0.0'

        instance = reckoner.course.Course(None)
        self.assertTrue(instance.plot(['a-chart-that-is-not-defined', 'fake-chart'])) 
開發者ID:FairwindsOps,項目名稱:reckoner,代碼行數:22,代碼來源:test_reckoner.py

示例11: get_cfg

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    #if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
    #    ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
開發者ID:schroederdewitt,項目名稱:mackrl,代碼行數:18,代碼來源:config.py

示例12: get_cfg

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
        ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
開發者ID:schroederdewitt,項目名稱:mackrl,代碼行數:18,代碼來源:config.py

示例13: get_cfg

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
開發者ID:schroederdewitt,項目名稱:mackrl,代碼行數:24,代碼來源:config.py

示例14: yaml_save

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def yaml_save(filename, data):
    """
    ***Converter Special ***

    Save contents of an OrderedDict structure to a yaml file

    :param filename: name of the yaml file to save to
    :param data: OrderedDict to save
    """

    sdata = convert_yaml(data)

    print(", saving to '{}'".format(os.path.basename(filename)+'.yaml'))
    if store_raw_output == True:
        with open(filename+'_raw.yaml', 'w') as outfile:
            outfile.write( sdata )

    # Test if roundtrip gives the same result
    data = yaml.load(sdata, yaml.RoundTripLoader)
    _yaml_save_roundtrip(filename, data) 
開發者ID:smarthomeNG,項目名稱:smarthome,代碼行數:22,代碼來源:item_conversion.py

示例15: _ordered_load

# 需要導入模塊: from ruamel import yaml [as 別名]
# 或者: from ruamel.yaml import load [as 別名]
def _ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
    """
    Ordered yaml loader
    Use this instead ot yaml.loader/yaml.saveloader to get an Ordereddict

    :param stream: stream to read from
    :param Loader: yaml-loader to use
    :object_pairs_hook: ...

    :return: OrderedDict structure
    """

    # usage example: ordered_load(stream, yaml.SafeLoader)
    class OrderedLoader(Loader):
        pass
    def construct_mapping(loader, node):
        loader.flatten_mapping(node)
        return object_pairs_hook(loader.construct_pairs(node))
    OrderedLoader.add_constructor(
        yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
        construct_mapping)
    return yaml.load(stream, OrderedLoader) 
開發者ID:smarthomeNG,項目名稱:smarthome,代碼行數:24,代碼來源:shyaml.py


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