本文整理汇总了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
示例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
示例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
示例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
示例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
示例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
示例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 = {}
示例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)
示例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'])
示例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']))
示例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
示例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
示例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
示例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)
示例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)