You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python PyYAML操作Kubernetes YAML添加注解输出为空如何解决

问题根因

你的代码输出为空有两个核心问题:

  1. yaml.safe_load_all() 返回的是一次性迭代生成器,不是持久化的文档列表。第一次for循环遍历完所有文档后,生成器已经耗尽,后续执行safe_dump_all时无法读取到任何内容,因此输出为空。
  2. PyYAML默认序列化逻辑不会给普通字符串自动添加单引号,无法满足你要求的输出格式。
可直接运行的修复代码
import yaml
import sys

# 自定义字符串序列化规则,强制输出单引号包裹的字符串
def _single_quote_str_representer(dumper, value):
    return dumper.represent_scalar("tag:yaml.org,2002:str", value, style="'")

yaml.add_representer(str, _single_quote_str_representer, Dumper=yaml.SafeDumper)

# 替换为你的目标YAML文件路径
target_file = "deployment.yaml"
docs = []
try:
    with open(target_file, "r", encoding="utf-8") as f:
        # 显式将生成器转为列表,持久化存储所有YAML文档
        docs = list(yaml.safe_load_all(f.read()))
except Exception:
    sys.exit(1)

for doc in docs:
    # 跳过YAML多文档分隔产生的空条目
    if not doc:
        continue
    if doc.get("kind") == "Deployment":
        pod_metadata = doc["spec"]["template"]["metadata"]
        if "annotations" not in pod_metadata:
            pod_metadata["annotations"] = {}
        pod_metadata["annotations"]["key"] = "val"

# 导出为标准K8s YAML块格式
yaml.safe_dump_all(
    documents=docs,
    stream=sys.stdout,
    default_flow_style=False,
    allow_unicode=True,
    encoding="utf-8"
)
关键修改说明
  • 将safe_load_all返回的生成器显式转换为列表,避免遍历耗尽后dump无内容的问题
  • 为SafeDumper注册自定义字符串表示器,所有字符串值输出时自动包裹单引号,符合格式要求
  • 增加空文档跳过逻辑,兼容多文档YAML中---分隔产生的空内容
  • dump时指定default_flow_style=False,输出K8s通用的缩进块结构,不会出现内联格式
  • 显式指定UTF-8编码,开启unicode支持,避免特殊字符乱码

内容的提问来源于stack exchange,提问作者sctx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 04:03:26