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


Python yaml.RoundTripDumper方法代码示例

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


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

示例1: create

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [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

示例2: create_tmp_file_from_contents

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [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

示例3: yaml_save_roundtrip

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [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

示例4: update_component_meta

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [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

示例5: create_user_says_skeleton

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def create_user_says_skeleton(self):
        template = os.path.join(self.template_dir, 'user_says.yaml')

        skeleton = {}
        for intent in self.assist._intent_action_funcs:
            # print(type(intent))
            entity_map_from_action = self.assist._intent_mappings.get(intent, {})

            d = yaml.compat.ordereddict()
            d['UserSays'] = [None, None]
            d['Annotations'] = [None, None]
            d['Events'] = [None]

            # d['Annotations'] = self.parse_annotations_from_action_mappings(intent)

            data = yaml.comments.CommentedMap(d)  # to preserve order w/o tags
            skeleton[intent] = data

        with open(template, 'a') as f:
            f.write('# Template for defining UserSays examples\n\n')
            f.write('# give-color-intent:\n\n')
            f.write('#  UserSays:\n')
            f.write('#    - My color is blue\n')
            f.write('#    - red is my favorite color\n\n')
            f.write('#  Annotations:\n')
            f.write('#    - blue: sys.color     # maps param value -> entity\n')
            f.write('#    - red: sys.color\n\n')
            f.write('#  Events:\n')
            f.write('#    - event1              # adds a triggerable event named \'event1\' to the intent\n\n\n\n')
            # f.write(header)
            yaml.dump(skeleton, f, default_flow_style=False, Dumper=yaml.RoundTripDumper) 
开发者ID:treethought,项目名称:flask-assistant,代码行数:33,代码来源:schema_handlers.py

示例6: create_entity_skeleton

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def create_entity_skeleton(self):
        print('Creating Template for Entities')
        template = os.path.join(self.template_dir, 'entities.yaml')
        message = """# Template file for entities\n\n"""

        skeleton = {}
        for intent in self.assist._intent_action_funcs:
            entity_map = self.assist._intent_mappings.get(intent)
            action_func = self.assist._intent_action_funcs[intent][0]
            args = inspect.getargspec(action_func).args

            # dont add API 'sys' entities to the template
            if entity_map:
                args = [a for a in args if 'sys.' not in entity_map.get(a, [])]

            for param in [p for p in args if p not in skeleton]:
                skeleton[param] = [None, None]

        with open(template, 'w') as f:
            f.write(message)
            f.write('#Format as below\n\n')
            f.write("# entity_name:\n")
            f.write("#  - entry1: list of synonyms \n")
            f.write("#  - entry2: list of synonyms \n\n")
            f.write("#For example:\n\n")
            f.write("# drink:\n")
            f.write("#  - water: ['aqua', 'h20'] \n")
            f.write("#  - coffee: ['joe', 'caffeine', 'espresso', 'late'] \n")
            f.write("#  - soda: ['pop', 'coke']\n\n\n\n")
            yaml.dump(skeleton, f, default_flow_style=False, Dumper=yaml.RoundTripDumper) 
开发者ID:treethought,项目名称:flask-assistant,代码行数:32,代码来源:schema_handlers.py

示例7: write

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def write(self):
        ''' write to file '''
        if not self.filename:
            raise YeditException('Please specify a filename.')

        if self.backup and self.file_exists():
            shutil.copy(self.filename, '{}{}'.format(self.filename, self.backup_ext))

        # Try to set format attributes if supported
        try:
            self.yaml_dict.fa.set_block_style()
        except AttributeError:
            pass

        # Try to use RoundTripDumper if supported.
        if self.content_type == 'yaml':
            try:
                Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
            except AttributeError:
                Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
        elif self.content_type == 'json':
            Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
        else:
            raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
                                 'Please specify a content_type of yaml or json.')

        return (True, self.yaml_dict) 
开发者ID:RedHatOfficial,项目名称:ansible-redhat_openshift_utils,代码行数:29,代码来源:oc_obj.py

示例8: _yaml_save_roundtrip

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

    sdata = yaml.dump(data, Dumper=yaml.RoundTripDumper, version=yaml_version, indent=indent_spaces, block_seq_indent=2, width=32768, allow_unicode=True)

    ldata = sdata.split('\n')
    rdata = []
    for index, line in enumerate(ldata):
        # Fix for ruamel.yaml handling: Reinsert empty line before comment of next section
        if len(line.lstrip()) > 0 and line.lstrip()[0] == '#':
            indentcomment = len(line) - len(line.lstrip(' '))
            indentprevline = len(ldata[index-1]) - len(ldata[index-1].lstrip(' '))
            if indentprevline - indentcomment >= 2*indent_spaces:
                rdata.append('')
            rdata.append(line)
        # Fix for ruamel.yaml handling: Remove empty line with spaces that have been inserted
        elif line.strip() == '' and line != '':
            if ldata[index-1] != '':
                rdata.append(line)
        else:
            rdata.append(line)

    sdata = '\n'.join(rdata)
    if sdata[0] == '\n':
        sdata =sdata[1:]

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

示例9: yaml_dump_roundtrip

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def yaml_dump_roundtrip(data):
    """
    Dump yaml to a string using the RoundtripDumper and correct linespacing in output file

    :param data: data structure to save
    """

    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 )
    return sdata 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:12,代码来源:shyaml.py

示例10: create_pipelined_model

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def create_pipelined_model(self):
        if os.path.exists(self.model_path):
            raise Exception("Model creation failed because it has already been created, model cache path is {}".format(
                self.model_path
            ))
        else:
            os.makedirs(self.model_path, exist_ok=False)
        for path in [self.variables_index_path, self.variables_data_path]:
            os.makedirs(path, exist_ok=False)
        shutil.copytree(os.path.join(file_utils.get_project_base_directory(), "federatedml", "protobuf", "proto"), self.define_proto_path)
        with open(self.define_meta_path, "w", encoding="utf-8") as fw:
            yaml.dump({"describe": "This is the model definition meta"}, fw, Dumper=yaml.RoundTripDumper) 
开发者ID:FederatedAI,项目名称:FATE,代码行数:14,代码来源:pipelined_model.py

示例11: to_fileobj

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def to_fileobj(self):
        """Dump this `YoloFile` contents to file-like object."""
        fp = utils.StringIO()
        yaml.dump(self._raw_content, fp, encoding='utf-8',
                  Dumper=yaml.RoundTripDumper)
        fp.seek(0)
        return fp 
开发者ID:rackerlabs,项目名称:yolo,代码行数:9,代码来源:yolo_file.py

示例12: render

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def render(self, **variables):
        # Render variables into the yolo file.
        template = jinja2.Template(
            yaml.dump(self._raw_content, Dumper=yaml.RoundTripDumper)
        )
        rendered_content = template.render(**variables)
        new_content = yaml.safe_load(rendered_content)
        return YoloFile(new_content) 
开发者ID:rackerlabs,项目名称:yolo,代码行数:10,代码来源:yolo_file.py

示例13: yaml2string

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def yaml2string(wf, pack, relpath, wd):
    s = [u'#!/usr/bin/env cwl-runner',
         yaml.dump(wf.to_obj(pack=pack, relpath=relpath, wd=wd),
                   Dumper=yaml.RoundTripDumper)]
    return u'\n'.join(s) 
开发者ID:NLeSC,项目名称:scriptcwl,代码行数:7,代码来源:yamlutils.py

示例14: list

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def list():
    """
    List all mod configuration
    """
    config_path = get_default_config_path()
    config = load_config(config_path, loader=yaml.RoundTripLoader)

    print(yaml.dump(config['mod'], Dumper=yaml.RoundTripDumper)) 
开发者ID:zhengwsh,项目名称:InplusTrader_Linux,代码行数:10,代码来源:__main__.py

示例15: dump_config

# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import RoundTripDumper [as 别名]
def dump_config(config_path, config, dumper=yaml.RoundTripDumper):
    with codecs.open(config_path, mode='w', encoding='utf-8') as file:
        file.write(yaml.dump(config, Dumper=dumper)) 
开发者ID:zhengwsh,项目名称:InplusTrader_Linux,代码行数:5,代码来源:config.py


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