你错了ruamel.yaml
无法处理标签。但是当然你必须提供如何处理任何未知标签的信息,它无法猜测你想要加载什么样的数据!Ref
:
import ruamel.yaml
yaml_str = """\
Properties:
MinSize: !Ref ClusterSize
MaxSize: !Ref ClusterSize
"""
class Blob(object):
def update(self, value):
self.value = value
def __str__(self):
return str(self.value)
def my_constructor(self, node):
data = Blob()
yield data
value = self.construct_scalar(node)
data.update(value)
ruamel.yaml.SafeLoader.add_constructor(u'!Ref', my_constructor)
data = ruamel.yaml.safe_load(yaml_str)
print('data', data['Properties']['MinSize'])
prints:
ClusterSize
如果你想摆脱许多不同的标签,并且不关心“一切都是字符串”,你也可以这样做:
import ruamel.yaml
yaml_str = """\
Properties:
MinSize: !Ref ClusterSize
MaxSize: !Ref ClusterSize
SizeList:
- !abc 1
- !xyz 3
"""
def general_constructor(loader, tag_suffix, node):
return node.value
ruamel.yaml.SafeLoader.add_multi_constructor(u'!', general_constructor)
data = ruamel.yaml.safe_load(yaml_str)
print(data)
这使:
{'Properties': {'SizeList': ['1', '3'], 'MinSize': 'ClusterSize', 'MaxSize': 'ClusterSize'}}
(请注意,标量1
and 3
作为字符串而不是普通整数加载)