如果有'!',如何使用PyYAML解析YAML在YAML内

问题描述 投票:3回答:2

我有一个YAML文件,我只想解析description变量;但是,我知道我的CloudFormation模板(YAML文件)中的感叹号给PyYAML带来了麻烦。

我收到以下错误:

yaml.constructor.ConstructorError: could not determine a constructor for the tag '!Equals'

该文件有许多!Ref!Equals。如何忽略这些构造函数并获取我正在寻找的特定变量 - 在本例中为description变量。

python constructor yaml amazon-cloudformation pyyaml
2个回答
1
投票

您可以使用自定义yaml.SafeLoader定义自定义构造函数

import yaml

doc = '''
Conditions: 
  CreateNewSecurityGroup: !Equals [!Ref ExistingSecurityGroup, NONE]
'''

class Equals(object):
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        return "Equals(%s)" % self.data

class Ref(object):
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        return "Ref(%s)" % self.data

def create_equals(loader,node):
    value = loader.construct_sequence(node)
    return Equals(value)

def create_ref(loader,node):
    value = loader.construct_scalar(node)
    return Ref(value)

class Loader(yaml.SafeLoader):
    pass

yaml.add_constructor(u'!Equals', create_equals, Loader)
yaml.add_constructor(u'!Ref', create_ref, Loader)
a = yaml.load(doc, Loader)
print(a)

输出:

{'Conditions': {'CreateNewSecurityGroup': Equals([Ref(ExistingSecurityGroup), 'NONE'])}}

3
投票

如果您必须处理具有多个不同标记的YAML文档,并且只对它们的一部分感兴趣,那么您仍然应该处理它们。如果您所支持的元素嵌套在其他标记结构中,则至少需要正确处理所有“封闭”标记。

但是,无需单独处理所有标记,您可以编写一个可以处理映射的构造函数例程,序列和标量将其注册到PyYAML的SafeLoader

import yaml

inp = """\
MyEIP:
  Type: !Join [ "::", [AWS, EC2, EIP] ]
  Properties:
    InstanceId: !Ref MyEC2Instance
"""

description = []

def any_constructor(loader, tag_suffix, node):
    if isinstance(node, yaml.MappingNode):
        return loader.construct_mapping(node)
    if isinstance(node, yaml.SequenceNode):
        return loader.construct_sequence(node)
    return loader.construct_scalar(node)

yaml.add_multi_constructor('', any_constructor, Loader=yaml.SafeLoader)

data = yaml.safe_load(inp)
print(data)

这使:

{'MyEIP': {'Type': ['::', ['AWS', 'EC2', 'EIP']], 'Properties': {'InstanceId': 'MyEC2Instance'}}}

inp也可以是一个打开阅读的文件)。

如上所示,如果您的代码中出现意外的!Join标记,以及!Equal等任何其他标记,也会继续工作。标签刚刚丢弃。

由于YAML中没有变量,因此“想要仅解析描述变量”是一种猜测。如果它有一个显式标记(例如!Description),你可以通过匹配any_constructor参数,通过向tag_suffix添加2-3行来过滤掉这些值。

    if tag_suffix == u'!Description':
        description.append(loader.construct_scalar(node))

然而,更有可能的是,映射中存在一些标量description,并且您对与该键相关联的值感兴趣。

    if isinstance(node, yaml.MappingNode):
        d = loader.construct_mapping(node)
        for k in d:
        if k == 'description':
            description.append(d[k])
        return d

如果您知道数据层次结构中的确切位置,您当然也可以使用data结构并根据键或列表位置提取所需的任何内容。特别是在那种情况下,你最好使用我的ruamel.yaml,这是否可以在没有额外努力的情况下在往返模式下加载标记的YAML(假设上面的inp):

from ruamel.yaml import YAML

with YAML() as yaml:
    data = yaml.load(inp)
© www.soinside.com 2019 - 2024. All rights reserved.