
您无法真正替换YAML中的字符串值,例如,某个字符串的子字符串将替换为另一个子字符串¹. 但是,YAML可以标记节点(在您的情况下,列表['a','b','c']并再次使用.
锚点的格式为&some_id,并在* some_id(不是节点)指定节点和别名节点之前插入.
这与字符串级替换不同,因为在解析YAML文件期间,可以保留引用. 就像在Python中为集合类型上的所有锚点加载YAML一样(例如cmd替换字符串,在标量上使用锚点时):

import sys import ruamel.yaml as yaml yaml_str = """\ sub: &sub0 [a, b, c] command: params: cmd1: type: string # Get the list defined in 'sub' enum : *sub0 description: Exclude commands from the test list. cmd2: type: string # Get the list defined in 'sub' enum: *sub0 """ data1 = yaml.load(yaml_str, Loader=yaml.RoundTripLoader) # the loaded elements point to the same list assert data1['sub'] is data1['command']['params']['cmd1']['enum'] # change in cmd2 data1['command']['params']['cmd2']['enum'][3] = 'X' yaml.dump(data1, sys.stdout, Dumper=yaml.RoundTripDumper, indent=4)
这将输出:
sub: &sub0 [a, X, c]
command:
params:
cmd1:
type: string
# Get the list defined in 'sub'
enum: *sub0
description: Exclude commands from the test list.
cmd2:
type: string
# Get the list defined in 'sub'
enum: *sub0

请注意,原始锚点名称仍然存在.
如果您不想在输出中使用锚点和别名,则可以在RoundTripDumper的RoundTripRepresenter子类中重写ignore_aliases方法(该方法有两个参数,但使用lambda * args: ...您不必须知道): <
dumper = yaml.RoundTripDumper dumper.ignore_aliases = lambda *args : True yaml.dump(data1, sys.stdout, Dumper=dumper, indent=4)

这使得:
sub: [a, X, c]
command:
params:
cmd1:
type: string
# Get the list defined in 'sub'
enum: [a, X, c]
description: Exclude commands from the test list.
cmd2:
type: string
# Get the list defined in 'sub'
enum: [a, X, c]
此技术可用于读取YAML文件,就好像您已完成字符串替换一样cmd替换字符串,通过重新读取转储的材料来忽略别名:

data2 = yaml.load(yaml.dump(yaml.load(yaml_str, Loader=yaml.RoundTripLoader),
Dumper=dumper, indent=4), Loader=yaml.RoundTripLoader)
# these are lists with the same value
assert data2['sub'] == data2['command']['params']['cmd1']['enum']
# but the loaded elements do not point to the same list
assert data2['sub'] is not data2['command']['params']['cmd1']['enum']
data2['command']['params']['cmd2']['enum'][5] = 'X'
yaml.dump(data2, sys.stdout, Dumper=yaml.RoundTripDumper, indent=4)
现在只有一个“ b”变成了“ X”:
sub: [a, b, c]
command:
params:
cmd1:
type: string
# Get the list defined in 'sub'
enum: [a, b, c]
description: Exclude commands from the test list.
cmd2:
type: string
# Get the list defined in 'sub'
enum: [a, X, c]
如上所述,仅当在集合类型上使用锚/别名时才需要,而在标量上使用时则不需要.
¹由于YAML可以创建对象,因此可能会产生影响
解析器是否创建了这些对象. 介绍如何执行此操作. 保留名称最初不可用,但已在ruamel.yaml更新中实现.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-259719-1.html
恶心
爱千玺