如何使用 PyYAML 更新 YAML 文件?

How to update YAML file using PyYAML?

如何评论“driverClassName”行并将 org.quartz.threadPool.threadCount 更新为 200

在下面的 YAML 片段中,使用 python(PyYAML 包)?

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties: 
     org.quartz.threadPool.threadCount: 50

PyYAML 无法添加注释。它实际上删除了所有关于加载的评论,所以一般来说 PyYAML 不是需要进一步人机交互的 YAML 文档的合适工具(这 我想这是添加评论的原因)。

您应该使用 ruamel.yaml(免责声明:我是该包的作者):

import sys
import ruamel.yaml

yaml_str = """\
PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties: 
     org.quartz.threadPool.threadCount: 50
"""
    
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['config'].yaml_add_eol_comment('this is the SQL driver', 'driverClassName', column=50)
data['spring']['properties']['org.quartz.threadPool.threadCount'] = 200
yaml.dump(data, sys.stdout)

给出:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver       # this is the SQL driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties:
    org.quartz.threadPool.threadCount: 200