亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在包含占位符的字典中加載 yaml 文件內容?

如何在包含占位符的字典中加載 yaml 文件內容?

MMMHUHU 2023-03-22 11:00:21
輸入yaml文件kind: Testingmetadata:   name: test-file   annotations:      purpose: To test the deployed codespec:   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
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

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


查看完整回答
反對 回復 2023-03-22
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號