Python yaml.Dumper() Examples
The following are 30
code examples of yaml.Dumper().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
yaml
, or try the search function
.
Example #1
Source File: __init__.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 6 votes |
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)
Example #2
Source File: __init__.py From BERT with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: templating.py From ocs-ci with MIT License | 6 votes |
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
Example #4
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #5
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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)
Example #6
Source File: config.py From blueoil with Apache License 2.0 | 6 votes |
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
Example #7
Source File: config.py From blueoil with Apache License 2.0 | 6 votes |
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
Example #8
Source File: item_conversion.py From smarthome with GNU General Public License v3.0 | 6 votes |
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
Example #9
Source File: item_conversion.py From smarthome with GNU General Public License v3.0 | 6 votes |
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)
Example #10
Source File: basics.py From director with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #11
Source File: inventory-converter-1.3-network_interfaces.py From bluebanquise with MIT License | 6 votes |
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}''')
Example #12
Source File: monolane_generator.py From terminus with Apache License 2.0 | 6 votes |
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)
Example #13
Source File: munch.py From vidcutter with GNU General Public License v3.0 | 6 votes |
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)
Example #14
Source File: extension.py From FTDAnsible with GNU General Public License v3.0 | 6 votes |
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
Example #15
Source File: default.py From parade with MIT License | 6 votes |
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)
Example #16
Source File: basics.py From costar_plan with Apache License 2.0 | 6 votes |
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
Example #17
Source File: __init__.py From pyRevit with GNU General Public License v3.0 | 6 votes |
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)
Example #18
Source File: frontmatter.py From sublime-markdown-popups with MIT License | 5 votes |
def yaml_dump(data, stream=None, dumper=yaml.Dumper): """Special dumper wrapper to modify the YAML dumper.""" class Dumper(dumper): """Custom dumper.""" # Handle Ordered Dict Dumper.add_representer( OrderedDict, lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items()) ) return yaml.dump(data, stream, Dumper, width=None, indent=4, allow_unicode=True, default_flow_style=False)
Example #19
Source File: test_storage.py From operator with Apache License 2.0 | 5 votes |
def assertRefused(self, obj): # We shouldn't allow them to be written with self.assertRaises(yaml.representer.RepresenterError): yaml.dump(obj, Dumper=storage._SimpleDumper) # If they did somehow end up written, we shouldn't be able to load them raw = yaml.dump(obj, Dumper=yaml.Dumper) with self.assertRaises(yaml.constructor.ConstructorError): yaml.load(raw, Loader=storage._SimpleLoader)
Example #20
Source File: config.py From barectf with MIT License | 5 votes |
def _yaml_ordered_dump(self, node, **kwds): class ODumper(yaml.Dumper): pass def dict_representer(dumper, node): return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, node.items()) ODumper.add_representer(collections.OrderedDict, dict_representer) return yaml.dump(node, Dumper=ODumper, **kwds)
Example #21
Source File: persistence.py From bionic with Apache License 2.0 | 5 votes |
def to_yaml(self): return yaml.dump( self._dict, default_flow_style=False, encoding=None, Dumper=YamlDumper, )
Example #22
Source File: config.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def dump_config(config_path, config, dumper=yaml.Dumper): dirname = os.path.dirname(config_path) if not os.path.exists(dirname): os.makedirs(dirname) with codecs.open(config_path, mode='w', encoding='utf-8') as stream: stream.write(to_utf8(yaml.dump(config, Dumper=dumper)))
Example #23
Source File: yaml_handler.py From Det3D with Apache License 2.0 | 5 votes |
def dump_to_fileobj(self, obj, file, **kwargs): kwargs.setdefault("Dumper", Dumper) yaml.dump(obj, file, **kwargs)
Example #24
Source File: site_yml.py From ceph-ansible-copilot with GNU Lesser General Public License v2.1 | 5 votes |
def write_yaml(yaml_file, yaml_data): with open(yaml_file, "w", 0) as out: ordered_dump(yaml_data, Dumper=yaml.SafeDumper, stream=out, default_flow_style=False, explicit_start=True)
Example #25
Source File: site_yml.py From ceph-ansible-copilot with GNU Lesser General Public License v2.1 | 5 votes |
def ordered_dump(data, stream=None, Dumper=yaml.Dumper, **kwds): 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)
Example #26
Source File: geometry.py From pyresample with GNU Lesser General Public License v3.0 | 5 votes |
def ordered_dump(data, stream=None, Dumper=yaml.Dumper, **kwds): """Dump the data to YAML in ordered fashion.""" class OrderedDumper(Dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), flow_style=False) OrderedDumper.add_representer(OrderedDict, _dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds)
Example #27
Source File: print_version_metadata.py From marketplace-k8s-app-tools with Apache License 2.0 | 5 votes |
def _ordered_dump(data, stream=None, dumper=yaml.Dumper, **kwds): class OrderedDumper(dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(collections.OrderedDict, _dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds)
Example #28
Source File: server.py From datapackage-pipelines with MIT License | 5 votes |
def yamlize(x): ret = yaml.dump(x, default_flow_style=False, Dumper=YAML_DUMPER) return ret
Example #29
Source File: yaml_handler.py From Det3D with Apache License 2.0 | 5 votes |
def dump_to_str(self, obj, **kwargs): kwargs.setdefault("Dumper", Dumper) return yaml.dump(obj, **kwargs)
Example #30
Source File: yaml_serializer.py From confluence-publisher with MIT License | 5 votes |
def dump(data, stream=None): return yaml.dump(data, stream=stream, Dumper=OrderedDumper, default_flow_style=False)