如何在包含占位符的字典中加载 yaml 文件内容?
How can I load a yaml file content in a dictionary containing placeholders?
输入yaml文件
kind: Testing
metadata:
name: test-file
annotations:
purpose: To test the deployed code
spec:
containers:
- name: client
image: {{.registry}}/xyz:{{.client}}
env:
{{ if ne .proxy "" }}
- name: http_proxy
value: "{{.proxy}}"
{{ end -}}
我想加载字典中除占位符内容之外的所有 yaml 内容。我怎样才能实现它?我可以使用任何正则表达式来过滤占位符吗?
我尝试使用以下代码,它适用于没有占位符值但在上述 yaml 中给出解析错误的 yaml。
def __load_yaml(filename):
with open(filename, 'r') as stream:
try:
return yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception
def main():
data = {}
data.update(__load_yaml(file))
print(data)
if __name__ == '__main__':
main()
我也试过这个,它正在加载yaml到字典,但也给出了FileNotFoundError。有没有办法将列表读取为流?或者有什么建议可以实现吗?:
def __load_yaml(filename):
with open(filename, 'r') as stream:
try:
data = []
for text in stream:
match = re.search(r'\{\{.*?\}\}', text)
if not match and text != None:
data.append(text)
with open(str(data), 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception
def __load_yaml(filename):
with open(filename, "r") as stream:
string = stream.read()
# Find placeholders
reg_one = re.findall(r':\{\{.*?\}\}', string)
reg_two = re.findall(r'\{\{.*?\}\}', string)
placeholders = reg_one + reg_two
# Replace placeholders
for placeholder in placeholders:
string = string.replace(placeholder, "")
try:
return yaml.load(string, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception
输入yaml文件
kind: Testing
metadata:
name: test-file
annotations:
purpose: To test the deployed code
spec:
containers:
- name: client
image: {{.registry}}/xyz:{{.client}}
env:
{{ if ne .proxy "" }}
- name: http_proxy
value: "{{.proxy}}"
{{ end -}}
我想加载字典中除占位符内容之外的所有 yaml 内容。我怎样才能实现它?我可以使用任何正则表达式来过滤占位符吗?
我尝试使用以下代码,它适用于没有占位符值但在上述 yaml 中给出解析错误的 yaml。
def __load_yaml(filename):
with open(filename, 'r') as stream:
try:
return yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception
def main():
data = {}
data.update(__load_yaml(file))
print(data)
if __name__ == '__main__':
main()
我也试过这个,它正在加载yaml到字典,但也给出了FileNotFoundError。有没有办法将列表读取为流?或者有什么建议可以实现吗?:
def __load_yaml(filename):
with open(filename, 'r') as stream:
try:
data = []
for text in stream:
match = re.search(r'\{\{.*?\}\}', text)
if not match and text != None:
data.append(text)
with open(str(data), 'r') as stream:
return yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception
def __load_yaml(filename):
with open(filename, "r") as stream:
string = stream.read()
# Find placeholders
reg_one = re.findall(r':\{\{.*?\}\}', string)
reg_two = re.findall(r'\{\{.*?\}\}', string)
placeholders = reg_one + reg_two
# Replace placeholders
for placeholder in placeholders:
string = string.replace(placeholder, "")
try:
return yaml.load(string, Loader=yaml.FullLoader)
except yaml.YAMLError as exception:
raise exception