如何要求 Python 更新 YAML 的变量?

How to ask Python to update the variables for 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>

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

这个:

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>>')