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


Python yaml.dump方法代码示例

本文整理汇总了Python中ruamel.yaml.dump方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.dump方法的具体用法?Python yaml.dump怎么用?Python yaml.dump使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ruamel.yaml的用法示例。


在下文中一共展示了yaml.dump方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: save_config

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def save_config(config, logdir):
  """Save a new configuration by name.

  If a logging directory is specified, is will be created and the configuration
  will be stored there. Otherwise, a log message will be printed.

  Args:
    config: Configuration object.
    logdir: Location for writing summaries and checkpoints if specified.

  Returns:
    Configuration object.
  """
  message = 'Start a new run and write summaries and checkpoints to {}.'
  print(message.format(logdir))
  config_path = os.path.join(logdir, 'config.yaml')
  yaml.dump(config, config_path, default_flow_style=False)
  return config 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:20,代码来源:utility.py

示例2: test_populate_config_by_yaml

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def test_populate_config_by_yaml(config_content, tmpdir):
    yaml_path = tmpdir.join("TEST.yaml")
    yaml_path.write(yaml.dump(config_content))
    config_read = get_config_by_yaml(str(yaml_path))
    assert config_read.channels == ["FOO-CHANNEL", "CHANNEL2"]
    assert config_read.get_all_channels() == [
        "FOO-CHANNEL",
        "CHANNEL2",
        "conda-forge",
        "anaconda",
        "main",
        "r",
    ]
    assert config_read.subdir == "SUBDIR"
    assert config_read.get_all_subdir() == ["SUBDIR", "noarch"]
    assert config_read.output == "OUTPUT"
    assert config_read.fatten
    assert config_read.skip_python
    assert not config_read.strip_symbols
    assert config_read.merge
    assert config_read.exclude_deps == {"EXCLUDE1", "EXCLUDE2"}
    assert config_read.add_deps == {"ADD1", "ADD2"}
    assert config_read.only_pypi
    assert not config_read.include_requirements 
开发者ID:regro,项目名称:conda-press,代码行数:26,代码来源:test_config.py

示例3: create_tmp_file_from_contents

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
        ''' create a file in tmp with name and contents'''

        tmp = Utils.create_tmpfile(prefix=rname)

        if ftype == 'yaml':
            # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
            # pylint: disable=no-member
            if hasattr(yaml, 'RoundTripDumper'):
                Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
            else:
                Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))

        elif ftype == 'json':
            Utils._write(tmp, json.dumps(data))
        else:
            Utils._write(tmp, data)

        # Register cleanup when module is done
        atexit.register(Utils.cleanup, [tmp])
        return tmp 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:23,代码来源:oc_obj.py

示例4: create

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def create(self, files=None, content=None):
        '''
           Create a config

           NOTE: This creates the first file OR the first conent.
           TODO: Handle all files and content passed in
        '''
        if files:
            return self._create(files[0])

        # pylint: disable=no-member
        # The purpose of this change is twofold:
        # - we need a check to only use the ruamel specific dumper if ruamel is loaded
        # - the dumper or the flow style change is needed so openshift is able to parse
        # the resulting yaml, at least until gopkg.in/yaml.v2 is updated
        if hasattr(yaml, 'RoundTripDumper'):
            content['data'] = yaml.dump(content['data'], Dumper=yaml.RoundTripDumper)
        else:
            content['data'] = yaml.safe_dump(content['data'], default_flow_style=False)

        content_file = Utils.create_tmp_files_from_contents(content)[0]

        return self._create(content_file['path'])

    # pylint: disable=too-many-function-args 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:27,代码来源:oc_obj.py

示例5: convert_yaml

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def convert_yaml(data):
    """
    ***Converter Special ***

    Convert data structure to yaml format

    :param data: OrderedDict to convert
    :return: yaml formated data
    """

    ordered = (type(data).__name__ == 'OrderedDict')
    if ordered:
        sdata = _ordered_dump(data, Dumper=yaml.SafeDumper, version=yaml_version, indent=indent_spaces, block_seq_indent=2, width=32768, allow_unicode=True, default_flow_style=False)
    else:
        sdata = yaml.dump(data, Dumper=yaml.SafeDumper, indent=indent_spaces, block_seq_indent=2, width=32768, allow_unicode=True, default_flow_style=False)
    sdata = _format_yaml_dump(sdata)

    return sdata 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:20,代码来源:item_conversion.py

示例6: _ordered_dump

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def _ordered_dump(data, stream=None, Dumper=yaml.Dumper, **kwds):
    """
    Ordered yaml dumper
    Use this instead ot yaml.Dumper/yaml.SaveDumper to get an Ordereddict

    :param stream: stream to write to
    :param Dumper: yaml-dumper to use
    :**kwds: Additional keywords

    :return: OrderedDict structure
    """

    # usage example: ordered_dump(data, Dumper=yaml.SafeDumper)
    class OrderedDumper(Dumper):
        pass
    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())
    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds) 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:23,代码来源:item_conversion.py

示例7: _format_yaml_dump

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def _format_yaml_dump(data):
    """
    Format yaml-dump to make file more readable
    (yaml structure must be dumped to a stream before using this function)
    | Currently does the following:
    | - Add an empty line before a new item

    :param data: string to format

    :return: formatted string
    """

    data = data.replace('\n\n', '\n')
    ldata = data.split('\n')
    rdata = []
    for index, line in enumerate(ldata):
        if line[-1:] == ':':
            # no empty line before list attributes
            if ldata[index+1].strip()[0] != '-':
                rdata.append('')
            rdata.append(line)
        else:
            rdata.append(line)
    fdata = '\n'.join(rdata)
    return fdata 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:27,代码来源:shyaml.py

示例8: yaml_save_roundtrip

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def yaml_save_roundtrip(filename, data, create_backup=False):
    """
    Dump yaml using the RoundtripDumper and correct linespacing in output file

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

    if not EDITING_ENABLED:
        return
    sdata = yaml.dump(data, Dumper=yaml.RoundTripDumper, version=yaml_version, indent=indent_spaces, block_seq_indent=block_seq_indent, width=12288, allow_unicode=True)
    sdata = _format_yaml_dump2( sdata )

    if not filename.lower().endswith('.yaml'):
        filename += YAML_FILE
    if create_backup:
        if os.path.isfile(filename):
            shutil.copy2(filename, filename+'.bak')

    with open(filename, 'w') as outfile:
        outfile.write( sdata ) 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:23,代码来源:shyaml.py

示例9: run_export

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def run_export():
    all_recs = MPost.query_all(kind='m', limit=10000)
    out_arr = []
    for postinfo in all_recs:
        out_arr.append(
            {
                'uid': postinfo.uid,
                'title': postinfo.title,
                'keywords': postinfo.keywords,
                'date': postinfo.date,
                'extinfo': postinfo.extinfo,
                'cnt_md': postinfo.cnt_md,
                'cnt_html': postinfo.cnt_html,
                'kind': postinfo.kind,
                'user_name': postinfo.user_name,
                'logo': '',
            }
        )

    dumper = ruamel.yaml.RoundTripDumper

    with open('xx_posts.yaml', 'w') as fo:
        yaml.dump(out_arr, fo, Dumper=dumper, allow_unicode=True) 
开发者ID:bukun,项目名称:TorCMS,代码行数:25,代码来源:script_posts_export.py

示例10: update_component_meta

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def update_component_meta(self, component_name, component_module_name, model_alias, model_proto_index):
        """
        update meta info yaml
        TODO: with lock
        :param component_name:
        :param component_module_name:
        :param model_alias:
        :param model_proto_index:
        :return:
        """
        with open(self.define_meta_path, "r", encoding="utf-8") as fr:
            define_index = yaml.safe_load(fr)
        with open(self.define_meta_path, "w", encoding="utf-8") as fw:
            define_index["component_define"] = define_index.get("component_define", {})
            define_index["component_define"][component_name] = define_index["component_define"].get(component_name, {})
            define_index["component_define"][component_name].update({"module_name": component_module_name})
            define_index["model_proto"] = define_index.get("model_proto", {})
            define_index["model_proto"][component_name] = define_index["model_proto"].get(component_name, {})
            define_index["model_proto"][component_name][model_alias] = define_index["model_proto"][component_name].get(model_alias, {})
            define_index["model_proto"][component_name][model_alias].update(model_proto_index)
            yaml.dump(define_index, fw, Dumper=yaml.RoundTripDumper) 
开发者ID:FederatedAI,项目名称:FATE,代码行数:23,代码来源:pipelined_model.py

示例11: print_service

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def print_service(service):
    cmap = ruamel.yaml.comments.CommentedMap()

    if 'name' in service:
        cmap['name'] = service['name']
    if 'id' in service:
        cmap['id'] = service['id']
    if 'description' in service:
        cmap['description'] = service['description']
    if 'bindable' in service:
        cmap['bindable'] = service['bindable']
    if 'metadata' in service:
        cmap['metadata'] = service['metadata']
    if 'plans' in service:
        cmap['plans'] = pretty_plans(service['plans'])

    print(ruamel.yaml.dump(cmap, Dumper=ruamel.yaml.RoundTripDumper)) 
开发者ID:ansibleplaybookbundle,项目名称:ansible-playbook-bundle,代码行数:19,代码来源:engine.py

示例12: update_property

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def update_property(project, property, value=None, types=None):
    if not types:
        types = import_classes
    path = (
        Path.cwd()
        / "Desktop"
        / "shared"
        / "project"
        / "eNMS"
        / "files"
        / "migrations"
        / project
    )
    for instance_type in types:
        with open(path / f"{instance_type}.yaml", "r") as migration_file:
            objects = yaml.load(migration_file)
        for obj in objects:
            obj["devices"] = []
            obj["pools"] = []
        with open(path / f"{instance_type}.yaml", "w") as migration_file:
            yaml.dump(objects, migration_file) 
开发者ID:eNMS-automation,项目名称:eNMS,代码行数:23,代码来源:migration.py

示例13: export_service

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def export_service(self, service_id):
        service = db.fetch("service", id=service_id)
        path = Path(self.path / "files" / "services" / service.filename)
        path.mkdir(parents=True, exist_ok=True)
        services = service.deep_services if service.type == "workflow" else [service]
        services = [service.to_dict(export=True) for service in services]
        for service_dict in services:
            for relation in ("devices", "pools", "events"):
                service_dict.pop(relation)
        with open(path / "service.yaml", "w") as file:
            yaml.dump(services, file)
        if service.type == "workflow":
            with open(path / "workflow_edge.yaml", "w") as file:
                yaml.dump(
                    [edge.to_dict(export=True) for edge in service.deep_edges], file
                )
        with open_tar(f"{path}.tgz", "w:gz") as tar:
            tar.add(path, arcname=service.filename)
        rmtree(path, ignore_errors=True) 
开发者ID:eNMS-automation,项目名称:eNMS,代码行数:21,代码来源:administration.py

示例14: prepare_config_file

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def prepare_config_file(test_case_config, it_config, args):
    config_path = args.nni_source_dir + test_case_config['configFile']
    test_yml_config = get_yml_content(config_path)

    # apply test case specific config
    if test_case_config.get('config') is not None:
        deep_update(test_yml_config, test_case_config['config'])

    # hack for windows
    if sys.platform == 'win32' and args.ts == 'local':
        test_yml_config['trial']['command'] = test_yml_config['trial']['command'].replace('python3', 'python')

    # apply training service config
    # user's gpuNum, logCollection config is overwritten by the config in training_service.yml
    # the hack for kubeflow should be applied at last step
    update_training_service_config(test_yml_config, args.ts)

    # generate temporary config yml file to launch experiment
    new_config_file = config_path + '.tmp'
    dump_yml_content(new_config_file, test_yml_config)
    print(yaml.dump(test_yml_config, default_flow_style=False), flush=True)

    return new_config_file 
开发者ID:microsoft,项目名称:nni,代码行数:25,代码来源:run_tests.py

示例15: to_yaml

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import dump [as 别名]
def to_yaml(self, filename=None, default_flow_style=False,
                    encoding="utf-8", errors="strict",
                    **yaml_kwargs):
            """
            Transform the Box object into a YAML string.

            :param filename:  If provided will save to file
            :param default_flow_style: False will recursively dump dicts
            :param encoding: File encoding
            :param errors: How to handle encoding errors
            :param yaml_kwargs: additional arguments to pass to yaml.dump
            :return: string of YAML or return of `yaml.dump`
            """
            return _to_yaml(self.to_dict(), filename=filename,
                            default_flow_style=default_flow_style,
                            encoding=encoding, errors=errors, **yaml_kwargs) 
开发者ID:zhou13,项目名称:lcnn,代码行数:18,代码来源:box.py


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