如何让Python更新YAML的变量?

时间:2017-02-27 03:28:27

标签: python yaml ruamel.yaml

我想从python获取值以将它们放入YAML中:

import ruamel.yaml

file_name = 'input.yml'
from ruamel.yaml.util import load_yaml_guess_indent

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

instances = config['instances']
print instances
instances['hostname'] = raw_input('What is the host name>>')
instances['syslog'] = raw_input ('what is the Syslog ip address>>')
instances['prefix'] = raw_input('What is the first prefix>>')
instances['prefix'] = raw_input ('what is the second address>>')

input.yml

---
instances:
      hostname: <name>              # update with IP
      syslog: <ip>    # update with user name
      interfaces:
         - name: GigabitEthernet0/0
           prefix: <first prefix>        
         - name: GigabitEthernet0/1
           prefix: <second prefix>

主机和系统日志部分正在运行,但我无法使前缀工作。

1 个答案:

答案 0 :(得分:1)

此:

instances['prefix'] = raw_input('What is the first prefix>>')
instances['prefix'] = raw_input ('what is the second address>>')

无效(如果可以的话,你会两次更新相同的东西)。您需要考虑prefix是序列元素(Python list)上的键,它是键interfaces的值:

instances['interfaces'][0]['prefix'] = raw_input('What is the first prefix>>')
instances['interfaces'][1]['prefix'] = raw_input ('what is the second address>>')