无法添加列表成员

时间:2019-05-24 15:53:20

标签: python yaml ruamel.yaml

我正在尝试添加一个新的列表成员,但没有成功。

这就是我所拥有的:

import sys
from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap as cm
from ruamel.yaml.comments import CommentedSeq as cs

yaml_doc = """\
Condition:
  Like:
    - !Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]
"""
yaml = YAML()
yaml.preserve_quotes = True
yaml.width = 4096
data = yaml.load(yaml_doc)
ref = data['Condition']['Like']

new_member = "!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '456', ':tty:*']]"
# new_member2 = '!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '456', ':tty:*']]'

ref.append(new_member)
# ref.append(new_member2)

yaml.dump(data, sys.stdout)

输出为

Condition:
  Like:
  - !Join ['', ['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]
  - "!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '456', ':tty:*']]"

我不要双引号。

如果我取消注释与new_member2相关的部分,则会出错

  File "ec2-recover-2.py", line 18
    new_member2 = '!Join ['',['abc: def: ', !Ref 'XYZ: : Rert', ': ', '456', ': tty: *']]'
                                 ^
SyntaxError: invalid syntax

如何添加!Join ['', ['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]格式的成员列表,并且在最终的YAML中没有单引号或双引号?

1 个答案:

答案 0 :(得分:0)

您似乎在想:

!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]

是普通标量,在Python中作为字符串加载。它不是。一种 纯标量不能以感叹号开头,因为YAML使用 引入tag, 而且您从那里加载的对象非常复杂:

import ruamel.yaml

yaml = ruamel.yaml.YAML()
data = yaml.load("!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]")
print(data)

打印:

['', ['abc:def:', <ruamel.yaml.comments.TaggedScalar object at 0x7f405265fa58>, ':', '123', ':tty:*']]

您可以从头开始构建此类对象,但是加载起来可能更容易 您要从其YAML字符串表示形式添加的列表项。如果你想自己动手做 也可以从CommentedSeqTaggedScalar实例构造条目:

import sys
from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedSeq as cs
from ruamel.yaml.comments import TaggedScalar as ts
from ruamel.yaml.scalarstring import SingleQuotedScalarString as sq

yaml_doc = """\
Condition:
  Like:
    - !Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]
"""
yaml = YAML()
yaml.preserve_quotes = True
yaml.width = 4096
data = yaml.load(yaml_doc)
ref = data['Condition']['Like']

new_member = yaml.load("!Join ['',['abc:def:', !Ref 'XYZ::Rert', ':', '456', ':tty:*']]")

ts1 = ts()
ts1.value = 'XYZ::Rert'
ts1.style = "'"
ts1.yaml_set_tag('!Ref')

new_member2 = cs([sq(''), [sq('abc:def:'), ts1 , sq(':'), sq('789'), sq(':tty:*')]])
new_member2.yaml_set_tag('!Join')
new_member2.fa.set_flow_style()

ref.append(new_member)
ref.append(new_member2)

yaml.dump(data, sys.stdout)

给出:

Condition:
  Like:
  - !Join ['', ['abc:def:', !Ref 'XYZ::Rert', ':', '123', ':tty:*']]
  - !Join ['', ['abc:def:', !Ref 'XYZ::Rert', ':', '456', ':tty:*']]
  - !Join ['', ['abc:def:', !Ref 'XYZ::Rert', ':', '789', ':tty:*']]

((如果您真的想弄清楚如何自己构建类似new_member2的东西,这会有所帮助 从YAML加载所需的输出并打印单个项目,其类型和 他们的属性)