本文整理汇总了Python中yaml.add_representer方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.add_representer方法的具体用法?Python yaml.add_representer怎么用?Python yaml.add_representer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yaml
的用法示例。
在下文中一共展示了yaml.add_representer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_yaml_file
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def save_yaml_file(path: str,
content: list or dict,
) -> None:
"""
Save a YAML file (usually an input / restart file, but also conformers file)
Args:
path (str): The YAML file path to save.
content (list, dict): The content to save.
"""
if not isinstance(path, str):
raise InputError(f'path must be a string, got {path} which is a {type(path)}')
yaml.add_representer(str, string_representer)
logger.debug('Creating a restart file...')
content = yaml.dump(data=content)
if '/' in path and os.path.dirname(path) and not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with open(path, 'w') as f:
f.write(content)
示例2: extract_substructure_for_test
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def extract_substructure_for_test(test_case, substructure, config):
"""
Extract the keys from the config in substructure, which may be a nested
dictionary.
Raises a ``unittest.SkipTest`` if the substructure is not found in the
configuration.
This can be used to load credentials all at once for testing purposes.
"""
try:
return extract_substructure(config, substructure)
except MissingConfigError as e:
yaml.add_representer(
Optional,
lambda d, x: d.represent_scalar(u'tag:yaml.org,2002:str', repr(x)))
test_case.skip(
'Skipping test: could not get configuration: {}\n\n'
'In order to run this test, add ensure file at $ACCEPTANCE_YAML '
'has structure like:\n\n{}'.format(
e.message,
yaml.dump(substructure, default_flow_style=False))
)
示例3: save_quasiparticle_data_to_file
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def save_quasiparticle_data_to_file(quasiparticle_data, filename):
import yaml
def float_representer(dumper, value):
text = '{0:.8f}'.format(value)
return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
yaml.add_representer(float, float_representer)
output_dict = []
for i, q_point in enumerate(quasiparticle_data['q_points']):
q_point_dict = {'reduced_wave_vector': q_point.tolist()}
q_point_dict.update({'frequencies': quasiparticle_data['frequencies'][i].tolist()})
q_point_dict.update({'linewidths': quasiparticle_data['linewidths'][i].tolist()})
q_point_dict.update({'frequency_shifts': quasiparticle_data['frequency_shifts'][i].tolist()})
# output_dict.update({'q_point_{}'.format(i): q_point_dict})
output_dict.append(q_point_dict)
with open(filename, 'w') as outfile:
yaml.dump(output_dict, outfile, default_flow_style=False)
示例4: save_mesh_data_to_yaml_file
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def save_mesh_data_to_yaml_file(mesh_data, filename):
import yaml
def float_representer(dumper, value):
text = '{0:.8f}'.format(value)
return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
yaml.add_representer(float, float_representer)
qpoints, multiplicity, frequencies, linewidths = mesh_data
output_dict = []
for i, qp in enumerate(qpoints):
mesh_dict = {}
mesh_dict['reduced_wave_vector'] = qp.tolist()
mesh_dict['frequencies'] = frequencies[i].tolist()
mesh_dict['linewidths'] = linewidths[i].tolist()
mesh_dict['multiplicity'] = int(multiplicity[i])
output_dict.append(mesh_dict)
with open(filename, 'w') as outfile:
yaml.dump(output_dict, outfile, default_flow_style=False)
示例5: __init__
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def __init__(self, full):
super(YamlOutput, self).__init__(full)
yaml.add_representer(six.text_type, self.string_presenter)
yaml.add_representer(str, self.string_presenter)
yaml.add_representer(collections.OrderedDict, self.dict_representer)
示例6: dump
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def dump(self):
dumpdata = {}
dumpdata['hosts'] = self.dump_hosts()
dumpdata['hostgroup'] = self.dump_hostgroups()
dumpdata['architecture'] = self.dump_arch()
dumpdata['environment'] = self.dump_env()
dumpdata['os'] = self.dump_os()
dumpdata['model'] = self.dump_model()
dumpdata['media'] = self.dump_media()
dumpdata['domain'] = self.dump_domain()
dumpdata['settings'] = self.dump_settings()
dumpdata['subnet'] = self.dump_subnet()
dumpdata['smart-proxy'] = self.dump_smartproxy()
dumpdata['partition-table'] = self.dump_ptable()
dumpdata['provisioning-template'] = self.dump_provisioningtpl()
dumpdata['users'] = self.dump_users()
dumpdata['users'] = self.dump_users()
dumpdata['auth-source-ldap'] = self.dump_ldaps()
dumpdata['usergroups'] = self.dump_usergroups()
dumpdata['roles'] = self.dump_roles()
# print the result
fmyml = { 'foreman': dumpdata }
def str_presenter(dumper, data):
try:
dlen = len(data.splitlines())
except TypeError:
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
if (dlen > 1):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
yaml.add_representer(unicode, str_presenter)
yaml.add_representer(str, str_presenter)
yml = yaml.dump(fmyml, allow_unicode=True, default_flow_style=False )
print( (yml) )
示例7: main
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def main():
"""
The main function for the Conformational FF optimization.
Note: it is crucial that the attom mapping is conserved between the representation in the Gaussian file
and the YAML coordinates file.
Command line argument:
'-f': The ESS output file (default: gaussian.out).
'-s': The FF box size in Angstroms (default: 10). Thumb-rule: 4 * radius (or 2 * diameter).
'-m': The custom Molecular Dynamics parameter .mdp filename (default: mdp.mdp).
Returns:
list: Entries are lists of coordinates (in array form) and energies (in kJ/mol).
"""
# Parse the command-line arguments (requires the argparse module)
args = parse_command_line_arguments()
t0 = time.time()
path = args.file[0]
size = args.size[0]
mdp_filename = args.mdp[0]
with open('coords.yml', 'r') as f:
coords = yaml.load(stream=f, Loader=yaml.FullLoader)
output = list()
for i, coord in enumerate(coords):
opt_xyz, e = amber_to_gromacs(g_path=path, coord=coord, size=size, mdp_filename=mdp_filename)
output.append([opt_xyz, e])
if i % 10 == 0:
purge()
purge()
# save YAML output
yaml.add_representer(str, string_representer)
content = yaml.dump(data=output, encoding='utf-8')
with open('output.yml', 'w') as f:
f.write(content)
dt = time.time() - t0
print(dt)
示例8: setup_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def setup_yaml():
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
yaml.add_representer(collections.OrderedDict, dict_representer)
yaml.add_representer(os._Environ, dict_representer)
yaml.add_representer(unicode, unicode_representer)
yaml.add_constructor(_mapping_tag, dict_constructor)
示例9: dump
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def dump(s, encoding='utf-8', save_unicode=False):
yaml.add_representer(str, represent_str)
yaml.add_representer(dict, represent_mapping)
# dump unicode as a str to remove '!!python/unicode' tag
if not save_unicode:
tag = u'tag:yaml.org,2002:str'
else:
tag = u'tag:yaml.org,2002:python/unicode'
yaml.add_representer(unicode, lambda dumper,
data: dumper.represent_scalar(tag, data))
if encoding is not None:
dumped = yaml.dump(s, allow_unicode=True, encoding=encoding)
else:
dumped = yaml.dump(s, allow_unicode=True, encoding='utf-8')
# unify encoding
dumped = unicode(dumped, 'utf-8')
# '...' is not necessary for yaml
pattern = '\.\.\.\n$'
return re.sub(pattern, '', dumped, 1)
示例10: save_params_dict_to_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def save_params_dict_to_yaml(params, file_path):
"""Saves the input ParamsDict to a YAML file."""
with tf.gfile.Open(file_path, 'w') as f:
def _my_list_rep(dumper, data):
# u'tag:yaml.org,2002:seq' is the YAML internal tag for sequence.
return dumper.represent_sequence(
u'tag:yaml.org,2002:seq', data, flow_style=True)
yaml.add_representer(list, _my_list_rep)
yaml.dump(params.as_dict(), f, default_flow_style=False)
示例11: __init__
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def __init__(self, state):
yaml.add_representer(dict, represent_dict)
self.state = _sort_with_priority(state)
示例12: write_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def write_yaml(data, yml_file):
Dumper = yaml.SafeDumper
Dumper.ignore_aliases = lambda self, data: True
yaml.add_representer(OrderedDict, represent_ordereddict, Dumper=Dumper)
return yaml.dump(data, yml_file, default_flow_style=False, Dumper=Dumper)
示例13: _write_pb_to_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def _write_pb_to_yaml(pb, output):
# Add yaml representer so that yaml dump can dump OrderedDict. The code
# is coming from https://stackoverflow.com/questions/16782112.
yaml.add_representer(OrderedDict, _represent_ordereddict)
json_obj = _order_dict(json.loads(MessageToJson(pb)))
with open(output, 'w') as outfile:
yaml.dump(json_obj, outfile, default_flow_style=False)
示例14: setup_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def setup_yaml():
""" https://stackoverflow.com/a/8661021 """
represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items()) # noqa
yaml.add_representer(OrderedDict, represent_dict_order)
示例15: setup_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import add_representer [as 别名]
def setup_yaml():
""" https://stackoverflow.com/a/8661021 """
represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items()) # noqa
yaml.add_representer(OrderedDict, represent_dict_order)