我使用PyYaml重新生成YAML文件,但是在转储的输出周围有不必要的尖括号:
源YAML文件:
Outputs:
HarvestApi:
Description: URL for application
Value: !Ref LocationRef
Export:
Name: HarvestApipython文件应该解析并转储YAML:
#!/usr/bin/env python3.6
import yaml
import sys
class RefTag(yaml.YAMLObject):
yaml_tag = u'Ref'
def __init__(self, text):
self.text = text
def __repr__(self):
return "%s( text=%r)" % ( self.__class__.__name__, self.text)
@classmethod
def from_yaml(cls, loader, node):
return RefTag(node.value)
@classmethod
def to_yaml(cls, dumper, data):
return dumper.represent_scalar(cls.yaml_tag, data.text)
yaml.SafeLoader.add_constructor('!Ref', RefTag.from_yaml)
yaml.SafeDumper.add_multi_representer(RefTag, RefTag.to_yaml)
yaml_list = None
with open("./yaml-test.yml", "r") as file:
try:
yaml_list = yaml.safe_load(file)
except yaml.YAMLError as exc:
print ("--", exc)
sys.exit(1)
print (yaml.dump(yaml_list, default_flow_style=False))但是,相反,输出如下:
Outputs:
HarvestApi:
Description: URL for application
Export:
Name: HarvestApi
Value: !<Ref> 'LocationRef'Ref对象周围的额外尖括号是我需要删除的。
发布于 2019-01-05 17:14:53
主要的问题是标签没有以感叹号开头。只是加上这会给你预期的输出。有关参考,请参见PyYAML类的Monster示例。
其他有问题的问题是:
.yamlRefTag上为SafeLoader注册加载程序和翻车程序,这很好,因为不需要使用默认的PyYAML Loader和Dumper。但是,您可以调用yaml.dump()而不是yaml.safe_dump()。前者起作用,但使用后者更好,因为它会抱怨数据结构中未注册的对象(当然,如果有,而不是输入,您现在正在使用)。所以,把事情改变为:
#!/usr/bin/env python3.6
import yaml
import sys
class RefTag(yaml.YAMLObject):
yaml_tag = u'!Ref'
def __init__(self, text):
self.text = text
def __repr__(self):
return "%s( text=%r)" % ( self.__class__.__name__, self.text)
@classmethod
def from_yaml(cls, loader, node):
return RefTag(node.value)
@classmethod
def to_yaml(cls, dumper, data):
return dumper.represent_scalar(cls.yaml_tag, data.text)
yaml.SafeLoader.add_constructor('!Ref', RefTag.from_yaml)
yaml.SafeDumper.add_multi_representer(RefTag, RefTag.to_yaml)
yaml_list = None
with open("./yaml-test.yaml", "r") as file:
try:
yaml_list = yaml.safe_load(file)
except yaml.YAMLError as exc:
print ("--", exc)
sys.exit(1)
yaml.safe_dump(yaml_list, sys.stdout, default_flow_style=False)这意味着:
Outputs:
HarvestApi:
Description: URL for application
Export:
Name: HarvestApi
Value: !Ref 'LocationRef'https://stackoverflow.com/questions/54053906
复制相似问题