如何将竖条(|)上的管道从Python添加到yaml文件中

2024-05-17 19:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务。我需要编写python代码来为kubernetes生成yaml文件。到目前为止,我一直在使用pyyaml,它工作得很好。以下是我生成的yaml文件:

apiVersion: v1
kind: ConfigMap
data:
  info: 
    name: hostname.com
    aio-max-nr: 262144
    cpu:
      cpuLogicalCores: 4
    memory:
      memTotal: 33567170560
    net.core.somaxconn: 1024
    ...

但是,当我尝试创建此configMap时,错误是info需要字符串()而不是映射。因此,我进行了一些探索,似乎解决这一问题的最简单方法是在如下信息之后添加管道:

apiVersion: v1
kind: ConfigMap
data:
  info: | # this will translate everything in data into a string but still keep the format in yaml file for readability
    name: hostname.com
    aio-max-nr: 262144
    cpu:
      cpuLogicalCores: 4
    memory:
      memTotal: 33567170560
    net.core.somaxconn: 1024
    ...

这样,我的configmap就成功创建了。我的问题是我不知道如何从python代码中添加管道条。在这里,我手动添加了它,但我想自动化整个过程

我编写的python代码的一部分是,假设数据是dict():

content = dict()
content["apiVersion"] = "v1"
content["kind"] = "ConfigMap"
data = {...}
info = {"info": data}
content["data"] = info

# Get all contents ready. Now write into a yaml file
fileName = "out.yaml"
with open(fileName, 'w') as outfile:
    yaml.dump(content, outfile, default_flow_style=False)   

我在网上搜索了很多案例,但没有一个符合我的需要。提前谢谢


Tags: 文件代码nameinfocomyamldatacontent
1条回答
网友
1楼 · 发布于 2024-05-17 19:43:58

管道使包含的值成为字符串。YAML不会处理该字符串,即使它包含具有YAML语法的数据。因此,您需要给出一个字符串作为值

由于字符串包含YAML语法中的数据,因此可以通过在上一步中使用YAML处理包含的数据来创建字符串。要使PyYAML以文本块样式转储标量(即使用|),您需要一个自定义的representer:

import yaml, sys
from yaml.resolver import BaseResolver

class AsLiteral(str):
  pass

def represent_literal(dumper, data):
  return dumper.represent_scalar(BaseResolver.DEFAULT_SCALAR_TAG,
      data, style="|")

yaml.add_representer(AsLiteral, represent_literal)

info = {
  "name": "hostname.com",
  "aio-max-nr": 262144,
  "cpu": {
    "cpuLogicalCores": 4
  }
}

info_str = AsLiteral(yaml.dump(info))

data = {
  "apiVersion": "v1",
  "kind": "ConfigMap",
  "data": {
    "info": info_str
  }
}

yaml.dump(data, sys.stdout)

通过将呈现的YAML数据放入类型AsLiteral,将调用已注册的自定义representer,它将所需样式设置为|

相关问题 更多 >