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


Python yaml.Dumper方法代码示例

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


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

示例1: toYAML

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def toYAML(self, **options):
        """ Serializes this Munch to YAML, using `yaml.safe_dump()` if
            no `Dumper` is provided. See the PyYAML documentation for more info.

            >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42)
            >>> import yaml
            >>> yaml.safe_dump(b, default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> b.toYAML(default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> yaml.dump(b, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'
            >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'

        """
        opts = dict(indent=4, default_flow_style=False)
        opts.update(options)
        if 'Dumper' not in opts:
            return yaml.safe_dump(self, **opts)
        else:
            return yaml.dump(self, **opts) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:24,代码来源:__init__.py

示例2: toYAML

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def toYAML(self, **options):
        """ Serializes this Bunch to YAML, using `yaml.safe_dump()` if 
            no `Dumper` is provided. See the PyYAML documentation for more info.
            
            >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42)
            >>> import yaml
            >>> yaml.safe_dump(b, default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> b.toYAML(default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> yaml.dump(b, default_flow_style=True)
            '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n'
            >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)
            '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n'
        """
        opts = dict(indent=4, default_flow_style=False)
        opts.update(options)
        if 'Dumper' not in opts:
            return yaml.safe_dump(self, **opts)
        else:
            return yaml.dump(self, **opts) 
开发者ID:yyht,项目名称:BERT,代码行数:23,代码来源:__init__.py

示例3: _save_config_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def _save_config_yaml(output_dir, config):
    file_name = 'config.yaml'
    config_dict = _easy_dict_to_dict(config)
    file_path = os.path.join(output_dir, file_name)

    class Dumper(yaml.Dumper):
        def ignore_aliases(self, data):
            return True
    Dumper.add_representer(ABCMeta, Representer.represent_name)

    if type(config_dict['CLASSES']) != list:
        DatasetClass = config.DATASET_CLASS
        dataset_kwargs = dict((key.lower(), val) for key, val in config.DATASET.items())
        train_dataset = DatasetClass(
            subset="train",
            **dataset_kwargs,
        )
        config_dict['CLASSES'] = train_dataset.classes

    with gfile.GFile(os.path.join(output_dir, file_name), 'w') as outfile:
        yaml.dump(config_dict, outfile, default_flow_style=False, Dumper=Dumper)

    return file_path 
开发者ID:blue-oil,项目名称:blueoil,代码行数:25,代码来源:config.py

示例4: convert_yaml

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

示例5: _ordered_dump

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

示例6: main

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def main():

    MyDumper.add_representer(dict, MyDumper.represent_dict_preserve_order)

    if len(sys.argv) != 2:
        usage(sys.argv[0])
        exit(1)

    hostsfile = sys.argv[1]
    outfile = hostsfile + '-bluebanquise-1.3'

    with open(hostsfile, 'r') as fd:
        try:
            inventory = yaml.load(fd, Loader=yaml.SafeLoader)
            new_inventory = search_network_interfaces(inventory)
        except yaml.YAMLError as exc:
            print(exc)

    with open(outfile, 'w') as fd:
        fd.write(yaml.dump(new_inventory, Dumper=MyDumper, default_flow_style=False))

    print(f'''Next steps:
      $ diff -u {hostsfile} {outfile} | less
      $ mv {outfile} {hostsfile}''') 
开发者ID:bluebanquise,项目名称:bluebanquise,代码行数:26,代码来源:inventory-converter-1.3-network_interfaces.py

示例7: _contents_as_string

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def _contents_as_string(self):
        """Convert the current monolane data into its yaml version.

        Preserves order of the keys inside of 'maliput_monolane_builder'.
        """
        header = "# -*- yaml -*-\n---\n# distances are meters; angles are degrees.\n"

        class OrderedDumper(yaml.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 header + yaml.dump(self.monolane, None, OrderedDumper) 
开发者ID:ekumenlabs,项目名称:terminus,代码行数:19,代码来源:monolane_generator.py

示例8: parse

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def parse(self, parser):
        def parse_arguments():
            args = [parser.parse_expression()]
            # append task filters if any
            if parser.stream.skip_if('comma'):
                args.append(parser.parse_expression())
            return args

        lineno = next(parser.stream).lineno
        tag_args = parse_arguments()
        call = self.call_method(self._include_tasks.__name__, tag_args)
        return Output([call], lineno=lineno)


# By default, `yaml` package does not preserve field order, and
# playbook tasks do not look the same as in playbooks and in docs.
# These functions create custom Loader and Dumper to preserve field order.
# Source: https://stackoverflow.com/a/21912744 
开发者ID:CiscoDevNet,项目名称:FTDAnsible,代码行数:20,代码来源:extension.py

示例9: create

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def create(self, flow, *tasks, deps=None):
        if not deps:
            deps = {}

        Flow(flow, tasks, deps)

        dep_lines = list(map(lambda x: x[0] + '->' + ','.join(x[1]), deps.items()))
        create_flow = {
            'tasks': list(tasks),
            'deps': dep_lines
        }

        class IndentDumper(yaml.Dumper):
            def increase_indent(self, flow=False, indentless=False):
                return super(IndentDumper, self).increase_indent(flow, False)

        os.makedirs(self.flow_dir, exist_ok=True)
        flow_file = os.path.join(self.flow_dir, flow + '.yml')
        with open(flow_file, 'w') as f:
            yaml.dump(create_flow, f, Dumper=IndentDumper, default_flow_style=False) 
开发者ID:bailaohe,项目名称:parade,代码行数:22,代码来源:default.py

示例10: to_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def to_yaml(obj):
    """ Simplify yaml representation for pretty printing """
    # Is there a better way to do this by adding a representation with yaml.Dumper?
    # Ordered dict: http://pyyaml.org/ticket/29#comment:11
    if obj is None or isstring(obj):
        out = str(obj)
    elif type(obj) in [int, float, bool]:
        return obj
    elif hasattr(obj, 'to_yaml'):
        out = obj.to_yaml()
    elif isinstance(obj, etree._Element):
    	out = etree.tostring(obj, pretty_print = True)
    elif type(obj) == dict:
        out = {}
        for (var, value) in obj.items():
            out[str(var)] = to_yaml(value)
    elif hasattr(obj, 'tolist'):
        # For numpy objects
        out = to_yaml(obj.tolist())
    elif isinstance(obj, collections.Iterable):
        out = [to_yaml(item) for item in obj]
    else:
        out = str(obj)
    return out 
开发者ID:jhu-lcsr,项目名称:costar_plan,代码行数:26,代码来源:basics.py

示例11: to_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def to_yaml(obj):
    """ Simplify yaml representation for pretty printing """
    # Is there a better way to do this by adding a representation with yaml.Dumper?
    # Ordered dict: http://pyyaml.org/ticket/29#comment:11
    if obj is None or isstring(obj):
        out = str(obj)
    elif type(obj) in [int, float, bool]:
        return obj
    elif hasattr(obj, 'to_yaml'):
        out = obj.to_yaml()
    elif isinstance(obj, etree._Element):
    	out = etree.tostring(obj, pretty_print = True)
    elif type(obj) == dict:
        out = {}
        for (var, value) in list(obj.items()):
            out[str(var)] = to_yaml(value)
    elif hasattr(obj, 'tolist'):
        # For numpy objects
        out = to_yaml(obj.tolist())
    elif isinstance(obj, collections.Iterable):
        out = [to_yaml(item) for item in obj]
    else:
        out = str(obj)
    return out 
开发者ID:RobotLocomotion,项目名称:director,代码行数:26,代码来源:basics.py

示例12: toYAML

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def toYAML(self, **options):
        """ Serializes this Munch to YAML, using `yaml.safe_dump()` if
            no `Dumper` is provided. See the PyYAML documentation for more info.

            >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42)
            >>> import yaml
            >>> yaml.safe_dump(b, default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> b.toYAML(default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> yaml.dump(b, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'
            >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'
        """
        opts = dict(indent=4, default_flow_style=False)
        opts.update(options)
        if 'Dumper' not in opts:
            return yaml.safe_dump(self, **opts)
        else:
            return yaml.dump(self, **opts) 
开发者ID:splunk,项目名称:SA-ctf_scoreboard,代码行数:23,代码来源:__init__.py

示例13: to_nice_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def to_nice_yaml(a, indent=2, *args, **kw):
    """
    This is a j2 filter which allows you from dictionary to print nice human
    readable yaml.

    Args:
        a (dict): dictionary with data to print as yaml
        indent (int): number of spaces for indent to be applied for whole
            dumped yaml. First line is not indented! (default: 2)
        *args: Other positional arguments which will be passed to yaml.dump
        *args: Other keywords arguments which will be passed to yaml.dump

    Returns:
        str: transformed yaml data in string format
    """
    transformed = yaml.dump(
        a,
        Dumper=yaml.Dumper,
        indent=indent,
        allow_unicode=True,
        default_flow_style=False,
        **kw
    )
    return transformed 
开发者ID:red-hat-storage,项目名称:ocs-ci,代码行数:26,代码来源:templating.py

示例14: __init__

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def __init__(self, *args, **kwargs):
        yaml.Dumper.__init__(self, *args, **kwargs)
        self.add_representer(OrderedDict, type(self).represent_ordereddict) 
开发者ID:fmenabe,项目名称:python-yamlordereddictloader,代码行数:5,代码来源:yamlordereddictloader.py

示例15: save_settings

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import Dumper [as 别名]
def save_settings(self):
    with open(self.settings_path, "w") as f:
      yaml.dump(self.settings, f, default_flow_style=False, Dumper=yaml.Dumper) 
开发者ID:LagoLunatic,项目名称:wwrando,代码行数:5,代码来源:randomizer_window.py


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