如何在python中使用ruamel库为数组添加新元素?

时间:2018-04-25 21:51:41

标签: python-3.x yaml ruamel.yaml

我有一个yaml文件,我想用ruamel更改。如果部署只包含一个环境,我可以更改它。问题是我想添加/更改多个环境。 下面是一个示例代码,它适用于使用2个参数的一个环境。

sample.py

select c.*, co.country
from coo c left join
     countries co
     on c.response like '%' + left(co.country, 4) + '%';

结果

sample.py mitul-trial test

import ruamel.yaml
import sys

file_name = 'Jenkinsfile.yaml'
from ruamel.yaml.util import load_yaml_guess_indent

config, ind, bsi = load_yaml_guess_indent(open(file_name))

totalArgs = len(sys.argv) - 1
print(totalArgs)
print(sys.argv[1:])

if totalArgs == 2:
    deploy = config['deploy']
    deploy[0]['env'] = sys.argv[1]
    deploy[0]['org'] = sys.argv[2]

elif totalArgs == 4:
    deploy = config['deploy']

    deploy[0]['env'] = sys.argv[1]
    deploy[0]['org'] = sys.argv[2]

    deploy[0]['env'] = sys.argv[3]
    deploy[0]['org'] = sys.argv[4]
    deploy[0]['host'] = 'https://**.com'
    deploy[0]['loc'] = 'saas'
    deploy[0]['manifest'] = 'manifest_dev.yml'
ruamel.yaml.round_trip_dump(config, open('Jenkinsfile.yaml', 'w'), 
                            indent=ind, block_seq_indent=bsi)

通缉结果:

sample.py mitul-trial test mitul1 testsomething

deploy:
- env: mitul-trial (Will change)
  org: test (Will change)
  host: https://**.com (will remain same)
  loc: saas (will remain same)
  manifest: manifest_dev.yml (will remain same)
  approval: true (will remain same)

1 个答案:

答案 0 :(得分:0)

您的代码无效,因为您没有在序列/列表中添加新元素,这是键deploy的值。您只是分配第一个条目的新值。

有几种方法可以复制这样的值,但由于它是一个dict,你需要确保你没有复制引用(这也会导致更新第一个元素)。在这种情况下,您最好使用标准库中的copy.deepcopy(),以确保安全。为此包括

from copy import deepcopy

因此,您elif代码应为:

elif totalArgs == 4:
    elem = deepcopy(config['deploy'][0])
    config['deploy'].append(elem)

    elem['env'] = sys.argv[1]
    elem['org'] = sys.argv[2]

    elem['env'] = sys.argv[3]
    elem['org'] = sys.argv[4]
    elem['host'] = 'https://**.com'
    elem['loc'] = 'saas'
    elem['manifest'] = 'manifest_dev.yml'

获得你想要的输出。