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


Python yaml.add_representer方法代码示例

本文整理汇总了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) 
开发者ID:ReactionMechanismGenerator,项目名称:ARC,代码行数:21,代码来源:common.py

示例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))
        ) 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:25,代码来源:testtools.py

示例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) 
开发者ID:abelcarreras,项目名称:DynaPhoPy,代码行数:23,代码来源:__init__.py

示例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) 
开发者ID:abelcarreras,项目名称:DynaPhoPy,代码行数:26,代码来源:__init__.py

示例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) 
开发者ID:DataBiosphere,项目名称:dsub,代码行数:8,代码来源:output_formatter.py

示例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) ) 
开发者ID:adfinis-sygroup,项目名称:foreman-yml,代码行数:41,代码来源:dump.py

示例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) 
开发者ID:ReactionMechanismGenerator,项目名称:ARC,代码行数:40,代码来源:mdconf.py

示例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) 
开发者ID:datawire,项目名称:forge,代码行数:8,代码来源:util.py

示例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) 
开发者ID:bsc-s2,项目名称:pykit,代码行数:28,代码来源:utfyaml.py

示例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) 
开发者ID:artyompal,项目名称:tpu_models,代码行数:11,代码来源:params_dict.py

示例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) 
开发者ID:nmstate,项目名称:nmstate,代码行数:5,代码来源:prettystate.py

示例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) 
开发者ID:innolitics,项目名称:rdm,代码行数:7,代码来源:util.py

示例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) 
开发者ID:googleapis,项目名称:artman,代码行数:10,代码来源:configure.py

示例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) 
开发者ID:CiscoDevNet,项目名称:virlutils,代码行数:6,代码来源:pyats_testbed.py

示例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) 
开发者ID:CiscoDevNet,项目名称:virlutils,代码行数:6,代码来源:ansible_inventory.py


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