本文整理汇总了Python中yaml.safe_dump方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.safe_dump方法的具体用法?Python yaml.safe_dump怎么用?Python yaml.safe_dump使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yaml
的用法示例。
在下文中一共展示了yaml.safe_dump方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initialize
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def initialize(ctx, legacy):
"""
Interactively create a paradrop.yaml file.
"""
if legacy:
chute = build_legacy_chute()
using = chute.get('use', None)
else:
chute = build_chute()
using = chute['services']['main'].get('image', None)
with open("paradrop.yaml", "w") as output:
yaml.safe_dump(chute, output, default_flow_style=False)
# If this is a node.js chute, generate a package.json file from the
# information that the user provided.
if using == 'node':
if not os.path.isfile('package.json'):
data = {
'name': chute['name'],
'version': '1.0.0',
'description': chute['description']
}
with open('package.json', 'w') as output:
json.dump(data, output, sort_keys=True, indent=2)
示例2: task_builddata
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def task_builddata(ctx, task_id=None, output='yaml'):
"""Show builddata assoicated with ``task_id``."""
if not task_id:
ctx.fail('The task id must be specified by --task-id')
task_bd = TaskBuildData(ctx.obj['CLIENT'], task_id=task_id).invoke()
if output == 'json':
click.echo(json.dumps(task_bd))
else:
if output != 'yaml':
click.echo(
'Invalid output format {}, defaulting to YAML.'.format(output))
click.echo(
yaml.safe_dump(
task_bd, allow_unicode=True, default_flow_style=False))
示例3: generate_configuration
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def generate_configuration(ctx, format):
"""
Generate a new node configuration based on detected hardware.
The new configuration is not automatically applied. Rather, you can
save it to file and use the import-configuration command to apply it.
"""
client = ctx.obj['client']
result = client.generate_config()
format = format.lower()
if format == 'json':
click.echo(json.dumps(result, indent=4))
elif format == 'yaml':
click.echo(yaml.safe_dump(result, default_flow_style=False))
else:
click.echo("Unrecognized format: {}".format(format))
return result
示例4: dump
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def dump(self, **kwargs):
"""Dump to a string."""
def convert_to_dict(cfg_node, key_list):
if not isinstance(cfg_node, CfgNode):
_assert_with_logging(
_valid_type(cfg_node),
"Key {} with value {} is not a valid type; valid types: {}".format(
".".join(key_list), type(cfg_node), _VALID_TYPES
),
)
return cfg_node
else:
cfg_dict = dict(cfg_node)
for k, v in cfg_dict.items():
cfg_dict[k] = convert_to_dict(v, key_list + [k])
return cfg_dict
self_as_dict = convert_to_dict(self, [])
return yaml.safe_dump(self_as_dict, **kwargs)
示例5: toYAML
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [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)
示例6: meta
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def meta(self, source, is_notebook=False):
if source is None:
return ''
if source.get('ipymd', {}).get('empty_meta', None):
return '---\n\n'
if not source:
if is_notebook:
return ''
return '---\n\n'
meta = '{}\n'.format(yaml.safe_dump(source,
explicit_start=True,
explicit_end=True,
default_flow_style=False))
if is_notebook:
# Replace the trailing `...\n\n`
meta = meta[:-5] + '---\n\n'
return meta
示例7: prompt_interactive
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def prompt_interactive(changes, project, package):
with tempfile.NamedTemporaryFile(mode='w', suffix='.yml') as temp:
temp.write(yaml.safe_dump(changes, default_flow_style=False, default_style="'") + '\n')
temp.write('# {}/{}\n'.format(project, package))
temp.write('# comment or remove lines to whitelist issues')
temp.flush()
editor = os.getenv('EDITOR')
if not editor:
editor = 'xdg-open'
subprocess.call(editor.split(' ') + [temp.name])
changes_after = yaml.safe_load(open(temp.name).read())
if changes_after is None:
changes_after = {}
return changes_after
示例8: dumps
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def dumps(data, use_yaml=None, safe=True, **kwds):
"""
Dumps data into a nicely formatted JSON string.
:param dict data: a dictionary to dump
:param kwds: keywords to pass to json.dumps
:returns: a string with formatted data
:rtype: str
"""
if use_yaml is None:
use_yaml = ALWAYS_DUMP_YAML
if use_yaml:
dumps = yaml.safe_dump if safe else yaml.dump
else:
dumps = json.dumps
kwds.update(indent=4, sort_keys=True)
if not safe:
kwds.update(default=repr)
return dumps(data, **kwds)
示例9: test_catalog_existing_remote_yml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def test_catalog_existing_remote_yml(settings):
from ideascube.serveradmin.catalog import Catalog
params = {
'id': 'foo', 'name': 'Content provided by Foo',
'url': 'http://foo.fr/catalog.yml'}
remotes_dir = Path(settings.CATALOG_STORAGE_ROOT).mkdir('remotes')
yml_file = remotes_dir.join('foo.yml')
yml_file.write(yaml.safe_dump(params))
c = Catalog()
remotes = c.list_remotes()
assert len(remotes) == 1
remote = remotes[0]
assert remote.id == params['id']
assert remote.name == params['name']
assert remote.url == params['url']
assert yml_file.check(exists=False)
json_data = json.loads(remotes_dir.join('foo.json').read())
assert json_data == params
示例10: test_catalog_remove_remote_yml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def test_catalog_remove_remote_yml(settings):
from ideascube.serveradmin.catalog import Catalog
params = {
'id': 'foo', 'name': 'Content provided by Foo',
'url': 'http://foo.fr/catalog.yml'}
remotes_dir = Path(settings.CATALOG_STORAGE_ROOT).mkdir('remotes')
yml_file = remotes_dir.join('foo.yml')
yml_file.write(yaml.safe_dump(params))
c = Catalog()
c.remove_remote(params['id'])
remotes = c.list_remotes()
assert len(remotes) == 0
assert yml_file.check(exists=False)
assert remotes_dir.join('foo.json').check(exists=False)
with pytest.raises(ValueError) as exc:
c.remove_remote(params['id'])
assert params['id'] in exc.exconly()
示例11: test_catalog_update_cache_yml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def test_catalog_update_cache_yml(tmpdir):
from ideascube.serveradmin.catalog import Catalog
remote_catalog_file = tmpdir.mkdir('source').join('catalog.yml')
remote_catalog_file.write(yaml.safe_dump({
'all': {'foovideos': {'name': 'Videos from Foo'}}}))
c = Catalog()
assert c._available == {}
assert c._installed == {}
c.add_remote(
'foo', 'Content from Foo',
'file://{}'.format(remote_catalog_file.strpath))
c.update_cache()
assert c._available == {'foovideos': {'name': 'Videos from Foo'}}
assert c._installed == {}
c = Catalog()
assert c._available == {'foovideos': {'name': 'Videos from Foo'}}
assert c._installed == {}
示例12: _remove_recipe_header
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def _remove_recipe_header(script_content):
"""
Removes the "hosts" and "connection" elements from the recipe
to make it "RADL" compatible
"""
try:
yamlo = yaml.safe_load(script_content)
if not isinstance(yamlo, list):
Tosca.logger.warn("Error parsing YAML: " + script_content + "\n.Do not remove header.")
return script_content
except Exception:
Tosca.logger.exception("Error parsing YAML: " + script_content + "\n.Do not remove header.")
return script_content
for elem in yamlo:
if 'hosts' in elem:
del elem['hosts']
if 'connection' in elem:
del elem['connection']
return yaml.safe_dump(yamlo, default_flow_style=False, explicit_start=True, width=256)
示例13: test_experiment_seq_seq_model_def_file
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def test_experiment_seq_seq_model_def_file(csv_filename, yaml_filename):
# seq-to-seq test to use model definition file instead of dictionary
input_features = [text_feature(reduce_output=None, encoder='embed')]
output_features = [
text_feature(reduce_input=None, vocab_size=3, decoder='tagger')
]
# Save the model definition to a yaml file
model_definition = {
'input_features': input_features,
'output_features': output_features,
'combiner': {'type': 'concat', 'fc_size': 14},
'training': {'epochs': 2}
}
with open(yaml_filename, 'w') as yaml_out:
yaml.safe_dump(model_definition, yaml_out)
rel_path = generate_data(input_features, output_features, csv_filename)
run_experiment(
None, None, data_csv=rel_path, model_definition_file=yaml_filename
)
示例14: create_yaml
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def create_yaml(_dict, file_name):
"""
Create or overwrite yaml file
:param dict: dict to be converted to yaml
:param filename: name of the yaml file to create
"""
def dump_yaml():
"""
Dumps the yaml into the file
"""
with open(file_name, 'w') as yaml_file:
yaml.safe_dump(_dict, yaml_file, default_flow_style=False)
if not os.path.isfile(file_name):
dump_yaml()
else:
should_overrite = input(
file_name+" already exists, would you like to overwrite it? (y/N):"
)
if should_overrite.lower() == 'y':
dump_yaml()
示例15: main
# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import safe_dump [as 别名]
def main(src_file, dst_file, **kwargs):
policies = []
with open(src_file, mode='rb') as f:
raw = f.read()
encoding = chardet.detect(raw)['encoding']
src = raw.decode(encoding).splitlines()
if '[Unicode]' in src:
policies = _convert_secedit(src)
else:
policies = _convert_regpol(src)
with open(dst_file, mode='w') as dh_:
yaml.safe_dump(policies, dh_, default_flow_style=False)