【发布时间】:2019-01-23 18:47:54
【问题描述】:
我有一些带有应用程序特定标签的 yaml(准确地说来自 AWS Cloud Formation 模板),如下所示:
example_yaml = "Name: !Join [' ', ['EMR', !Ref 'Environment', !Ref 'Purpose']]"
我想解析它以便我可以这样做:
>>> print(result)
>>> {'Name': 'EMR {Environment} {Purpose}'}
>>> name = result['name'].format(
... Environment='Development',
... Purpose='ETL'
... )
>>> print(name)
>>> EMR Development ETL
目前我的代码如下所示:
import yaml
from pprint import pprint
def aws_join(loader, node):
join_args = loader.construct_yaml_seq(node)
delimiter = list(join_args)[0]
joinables = list(join_args)[1]
join_result = delimiter.join(joinables)
return join_result
def aws_ref(loader, node):
value = loader.construct_scalar(node)
placeholder = '{'+value+'}'
return placeholder
yaml.add_constructor('!Join', aws_join)
yaml.add_constructor('!Ref', aws_ref)
example_yaml = "Name: !Join [' ', ['EMR', !Ref 'Environment', !Ref 'Purpose']]"
pprint(yaml.load(example_yaml))
很遗憾,这会导致错误。
...
joinables = list(join_args)[1]
IndexError: list index out of range
将print('What I am: '+str(join_args)) 添加到aws_join 表明我得到了一个生成器:
What I am: <generator object SafeConstructor.construct_yaml_seq at 0x1082ece08>
这就是我尝试将生成器转换为列表的原因。生成器最终会正确填充,只是没有及时让我使用它。如果我将 aws_join 函数更改为这样:
def aws_join(loader, node):
join_args = loader.construct_yaml_seq(node)
return join_args
那么最终的结果是这样的:
{'Name': [' ', ['EMR', '{Environment}', '{Purpose}']]}
所以我的功能所需的部分就在那里,只是在我的功能中需要它们时没有。
【问题讨论】: