【问题标题】:Delete blocks in YAML file using Python使用 Python 删除 YAML 文件中的块
【发布时间】:2022-01-06 18:47:11
【问题描述】:

我有一个包含 Jenkins 配置的 YAML 文件,如下所示:

credentials:
  system:
    domainCredentials:
    - credentials:
      - usernamePassword:
          description: "github"
          id: "github"
          password: "{AQAAABAAAAAwHFhIFIYeda2gWu9qfLX8fRAOlQjdb+Eyo3K9EoYSCxT6nrTLt+QRKSBo4Sx4qOXH1Lfn2EjfAQfklR63XqWZAw==}"
          scope: GLOBAL
          username: "admin"
      - string:
          description: "test"
          id: "test"
          scope: GLOBAL
          secret: "{AQAAABAAAAAQyWoMCVDAldVDxS1J15gLzqTvo2Dr6j3ckrdX3C1/3sg=}"
jenkins:
  agentProtocols:
  - "JNLP4-connect"
  - "Ping"
  authorizationStrategy:
    loggedInUsersCanDoAnything:
      allowAnonymousRead: false
  crumbIssuer:
    standard:
      excludeClientIPFromCrumb: false
  disableRememberMe: false
  labelAtoms:
  - name: "master"
  markupFormatter: "plainText"
  mode: NORMAL
  myViewsTabBar: "standard"
  numExecutors: 2
  primaryView:
    all:
      name: "all"
  projectNamingStrategy: "standard"
  quietPeriod: 5
  remotingSecurity:
    enabled: true
  scmCheckoutRetryCount: 0
  securityRealm:
    local:
      allowsSignup: false
      enableCaptcha: false
      users:
      - id: "admin"
        name: "admin"
        properties:
        - "myView"
        - preferredProvider:
            providerId: "default"
        - "timezone"
        - mailer:
            emailAddress: "admin@test.net"
        - "apiToken"
  slaveAgentPort: 50000
  updateCenter:
    sites:
    - id: "default"
      url: "https://updates.jenkins.io/update-center.json"
  views:
  - all:
      name: "all"
  viewsTabBar: "standard"
security:
  apiToken:
    creationOfLegacyTokenEnabled: false
    tokenGenerationOnCreationEnabled: false
    usageStatisticsEnabled: true
  sSHD:
    port: -1
unclassified:
  artifactoryBuilder:
    jfrogPipelinesServer:
      bypassProxy: false
      connectionRetries: 3
      credentialsConfig:
        overridingCredentials: false
        username: "****"
      timeout: 300
    useCredentialsPlugin: false
  buildDiscarders:
    configuredBuildDiscarders:
    - "jobBuildDiscarder"
  buildStepOperation:
    enabled: false
  email-ext:
    adminRequiredForTemplateTesting: false
    allowUnregisteredEnabled: false
    charset: "UTF-8"
    debugMode: false
    defaultBody: |-
      $PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:

      Check console output at $BUILD_URL to view the results.
    defaultSubject: "$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!"
    defaultTriggerIds:
    - "hudson.plugins.emailext.plugins.trigger.FailureTrigger"
    maxAttachmentSize: -1
    maxAttachmentSizeMb: -1
    precedenceBulk: false
    watchingEnabled: false
  fingerprints:
    fingerprintCleanupDisabled: false
    storage: "file"
  gitHubConfiguration:
    apiRateLimitChecker: ThrottleForNormalize
  gitHubPluginConfig:
    hookUrl: "http://localhost:8080/github-webhook/"
  gitSCM:
    addGitTagAction: false
    allowSecondFetch: false
    createAccountBasedOnEmail: false
    disableGitToolChooser: false
    hideCredentials: false
    showEntireCommitSummaryInChanges: false
    useExistingAccountWithSameEmail: false
  ivyBuildTrigger:
    extendedVersionMatching: false
  junitTestResultStorage:
    storage: "file"
  location:
    adminAddress: "address not configured yet <nobody@nowhere>"
    url: "http://localhost:8080/"
  mailer:
    charset: "UTF-8"
    useSsl: false
    useTls: false
  mavenModuleSet:
    localRepository: "default"
  pollSCM:
    pollingThreadCount: 10
  timestamper:
    allPipelines: false
    elapsedTimeFormat: "'<b>'HH:mm:ss.S'</b> '"
    systemTimeFormat: "'<b>'HH:mm:ss'</b> '"
tool:
  git:
    installations:
    - home: "git"
      name: "Default"
  mavenGlobalConfig:
    globalSettingsProvider: "standard"
    settingsProvider: "standard"

我需要删除两个块“未分类:”和“位置:”,如何使用 Python 做到这一点?

【问题讨论】:

  • 您是否尝试过读取 YAML 文件、将其转换为 Python 数据结构、删除部分、将其转换回 YAML 并再次将其保存到文件中?

标签: python yaml


【解决方案1】:

您可以使用pyyaml 模块来执行此操作。这是一个例子:

import yaml

with open('file.yaml', 'r') as file:
    data = yaml.safe_load(file)
data.pop('unclassified')
with open('file.yaml', 'w') as file:
    yaml.safe_dump(data, file)

【讨论】:

  • 当运行 python3 script.py 时它不起作用>> Traceback(最近一次调用最后):文件“script.py”,第 5 行,在 del data['unclassifed'] KeyError:'未分类'
  • 我只是在“未分类”这个词中犯了一个错误,但现在代码是正确的。
  • 感谢它正在工作,但文件格式已更改,
  • 嗯,它可能已经改变了一点,但我相信它仍然是正确的。可能有一些关键字参数可以与 safe_dump 函数一起使用以保持以前的格式,但我不确定这一点。
  • 我试图删除它给我的“位置”块,>> KeyError:'位置'>>我注意到它只能删除主要块,但子块会出错
猜你喜欢
  • 2017-01-03
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 2014-04-07
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多