设置:
我有两个 YAML 文件:一个带有标签和别名的大文件,另一个带有大文件中的一些键值对的小文件。我正在使用 python2.7。
问题:
我想用小的值更新大的值。
挑战:
小 yaml 可以包含大 yaml 中存在的键值对的任意组合。我还必须保留大的文字结构(不解析标签/别名)。大的很复杂,包含字典列表的字典(不要问......)。这可能吗?
特别是对于这样的事情:
resources: &something
that_thing: some_stuff
some_other_stuff: this_thing
例如我想得到的:
resources: &something
that_thing: some_stuff
some_other_stuff: this_thing_updated
因为这不太适合字典(我认为?)
请您参考如下方法:
如果小文件的键在大文件中是唯一的,那么遍历大文件的数据结构并更新它的值就相对简单,如果这些键:
import sys
import ruamel.yaml
big_yaml = """\
resources: &something
that_thing: !SomeStuff
a:
- 1
- some_stuff: d
b: *something
some_other_stuff: this_thing
"""
small_yaml = """\
some_stuff: 42
some_other_stuff: 'the_other_thing'
"""
def walk_tree(d, update, done=set()):
if not update:
return
if id(d) in done:
return
if isinstance(d, dict):
done.add(id(d))
for k in d:
if k in update:
d[k] = update.pop(k)
continue # don't recurse in the newly updated value
walk_tree(d[k], update) # recurse into the values
elif isinstance(d, list):
done.add(id(d))
for elem in d:
walk_tree(elem, update)
# doing nothing for leaf-node scalars
yaml = ruamel.yaml.YAML()
# yaml.indent(mapping=2, sequence=2, offset=0)
yaml.preserve_quotes = True
big = yaml.load(big_yaml)
small = yaml.load(small_yaml)
# print(data)
walk_tree(big, small)
yaml.dump(big, sys.stdout)
给出:
resources: &something
that_thing: !SomeStuff
a:
- 1
- some_stuff: 42
b: *something
some_other_stuff: 'the_other_thing'
请注意:
- 您需要保留节点的
id集合,以防止无限递归。这当然只有在您的大数据是递归的情况下才有必要,但这不会有坏处。 - 我
popupdate的值,因此小文件变空,递归提前停止。如果你想更新所有匹配的键,那么不要pop,只需分配(然后你可以从walk_tree中删除前两行) - 标记被保留,即使程序不知道如何创建
!Somestuff类。这是一种魔法! - 目前只有当有一个实际的别名引用它时才会转储 anchor 。 anchor 被保留,所以
ruamel.yaml可能会被修补以始终转储 anchor (通常,当还添加在数据树中多次表示的新元素时,这可能会导致冲突和需求额外检查) - 保留围绕“the_other_thing”的多余引号
- 你的映射resp。序列缩进需要保持一致,否则它们会被重新格式化。您可以取消注释
yaml.indent行并调整值(以匹配大文件)
或者,您可以使用如下所示的小型 YAML:
[resources, that_thing, a, 1, some_stuff]: 42
[resources, some_other_stuff]: 'the_other_thing'
然后您可以根据键序列元素对数据结构进行确定性递归,取消检查 id 并沿 update 拖动(只需将值作为 的第二个参数传递walk_tree).
如果你所有的更新都在大文件的顶层。那么这些递归都不是必需的,因为这只是上述的一个简单的极端情况。
