我一直在使用ruamel yaml编辑我的YAML文件并将其转回。我需要帮助来了解如何保持与原始文件相同的结构,因为我要做的就是复制,编辑并再次写入。
例如,这是原始文件:
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
-
Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
新文件看起来不一样:
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
- Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
最大的问题是,我使用了ruamel必须解决的各种技巧,但是每次yaml的不同部分都会中断。
这是我的功能:
def editEndpointServiceTemplate(endpoint_service_template_path):
yaml = YAML()
yaml.preserve_quotes = True
# yaml.compact(seq_seq=False, seq_map=False)
# yaml.indent(mapping=4, sequence=3, offset=0)
#Load yaml file
with open(endpoint_service_template_path) as fp:
data = yaml.load(fp)
#Edit the yaml
data['Description'] = "CloudFormation"
#Write new yaml file
with open(endpoint_service_template_path, 'w') as fp:
yaml.dump(data, fp)
正如您在注释命令中看到的那样,我修改了设置,但找不到最佳位置。
在这种情况下,很明显您的函数没有产生您当前显示的输出(缩进不同,单词“ CloudFormation”缺失),但是通常您应该注意以下问题:程序是相同的,并且程序是完整的,因此可以得到结果可以更容易地复制。
ruamel.yaml
没有为所有很少见的格式内置函数,但是您的方法相对接近于使用该方法的输出,.indent(mapping=4, sequence=4, offset=2)
并通过逐行检查进行转换。
由于使用字符串标量的可能性较小,因此您需要一个序列指示符后接三个空格(“ -
”)(另外,还必须将其包装成一行以成为行上的第一个非空格),因此最好进行以下.indent(mapping=4, sequence=4, offset=0)
转换:
import sys
import ruamel.yaml
yaml_str = """\
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
-
Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
"""
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=4, sequence=4, offset=0)
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
data['Description'] = "CloudFormation"
def break_seq(s):
result = []
PAT = '- '
for line in s.splitlines():
ls_line = line.lstrip()
if ls_line.startswith(PAT):
line = line.replace(PAT, ' - \n' + ' ' * (line.index(PAT) + 4))
result.append(line)
return '\n'.join(result)
yaml.dump(data, sys.stdout, transform=break_seq)
这使:
ElasticLoadBalancingV2Listener:
Type: "AWS::ElasticLoadBalancingV2::Listener"
Properties:
LoadBalancerArn: !Ref ElasticLoadBalancingV2LoadBalancer
Port: !FindInMap [NLBPorts, Port1, Port]
Protocol: "TCP"
DefaultActions:
-
Order: 1
TargetGroupArn: !Ref ElasticLoadBalancingV2TargetGroup1
Type: "forward"
Description: CloudFormation
可以通过“破解”序列化到序列中的例程来完成上述操作,但是,尽管在时间/空间使用上效率不高,但仅转换输出通常会更容易。
除非使用此输出的程序使用了不完整的YAML解析器,否则加载的实际数据结构不会改变,对于那些不习惯这种格式的人来说,其可读性会降低。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句