本文整理匯總了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)
示例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)
示例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
示例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
示例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)
示例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}''')
示例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)
示例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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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)