【问题标题】:python insert yaml in a yaml as inline or stringpython在yaml中插入yaml作为内联或字符串
【发布时间】:2020-04-30 21:03:55
【问题描述】:

您好,我正在尝试在 yaml 文件中读取插入项,该文件在 yaml 中包含 yaml,因为字符串后面是 yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa

我想在这样的目标中插入一个新的 url

apiVersion: v1
kind: ConfigMap
metadata:
  name: conf
  labels:
    name: conf
  namespace: conf
data:
  blackbox.yml: |
    - labels:
        module: http_2xx_get
      targets:
      - https://xxx.asd.com/pa
      - https://xxx1.asd.com/pa

以下是我要插入的代码。它认为是字符串,不能正常工作。

import yaml

probes = {"app": "/Users/asd/prometheus-configmap.yml"}

with open(probes['app'], 'r') as file:
    app_list = yaml.load(file, Loader=yaml.FullLoader)

    probes = yaml.safe_load(app_list['data']['blackbox.yml'])
    probes[0]['targets'].append("https://xxx1.asd.com/pa")
    with open("test.yml", "w") as yaml_file:
        yaml.dump(app_list, yaml_file)

yaml 文件的输出:

apiVersion: v1
data:
  blackbox-flights.yml: "- labels:\n    module: http_2xx_get\n  targets:\n  - https://xxx.asd.com/pa\n\
    \  - https://xxx1.asd.com/pa\n"
kind: ConfigMap
metadata:
  labels:
    name: conf
  name: conf
  namespace: conf

【问题讨论】:

  • 您应该缩进以probes = 开头的四行。 file 是内置的(用于 Python2),因此可能不是一个好的变量名。自 2006 年以来,YAML 文件的推荐扩展名一直是 .yaml

标签: python yaml pyyaml


【解决方案1】:

我使用了来自here 的以下解决方案,并且工作正常。

感谢@Gary van der Merwe

这是我的代码:

class literal_unicode(str):
    pass


def literal_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

import yaml

probes = {"app": "/Users/asd/prometheus-configmap.yml"}

with open(probes['app'], 'r') as file:
    app_list = yaml.load(file, Loader=yaml.FullLoader)

    probes = yaml.safe_load(app_list['data']['blackbox.yml'])
    probes[0]['targets'].append("https://xxx1.asd.com/pa")
    yaml.add_representer(literal_unicode, literal_unicode_representer)
    data = {
        'blackbox.yml': literal_unicode(yaml.dump(probes))}
    app_list['data'] = data
    with open("test.yml", "w") as yaml_file:
        yaml.dump(app_list, yaml_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 2012-11-22
    • 2011-10-14
    • 2023-03-24
    • 2021-06-13
    相关资源
    最近更新 更多