PyYAML使用

install

yum -y install PyYAML

document

http://www.showyounger.com/show/101586.html
http://pyyaml.org/wiki/PyYAMLDocumentation

yaml.load() 将yaml文档处理为python对象
yaml.dump() 将python对象处理为yaml文档

example

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import yaml

with file('/tmp/dashboard.yaml', 'r') as f:
    content = yaml.load(f)
    print content['web']['login'], content['web']['password'], content['interval']

    for switch in content['switch']:
        print switch['name'], switch['ip'], switch['snmp'], switch['port'] 

    new = {'name': 'bj', 'ip': '192.168.1.100', 'community': 'passwd', 'port': 'GigabitEthernet 0/48', 'bandwidth': 10000}
    content['switch'].append(new)

with file('/tmp/dashboard.yaml', 'w') as f:
    f.write(yaml.dump(content, indent=4, default_flow_style=False))
    # yaml.dump(content, f) 

flow_style

interval: 60
switch:
- {ip: 192.168.3.100, name: gz, port: Port-channel 1, community: passwd, band 300}
- {ip: 192.168.2.100, name: sh, port: Port-channel 4, community: passwd, band 1000}
- {ip: 192.168.1.100, name: bj, port: GigabitEthernet 0/48, community: passwd, band 10000}
web: {login: admin, password: 123456}
interval: 60
switch:
-   ip: 192.168.3.100
    name: gz
    port: Port-channel 1
    community: passwd
    band 300
-   ip: 192.168.2.100
    name: sh
    port: Port-channel 4
    community: passwd
    band 1000
-   ip: 192.168.1.100
    name: bj
    port: GigabitEthernet 0/48
    community: passwd
    band 10000
web:
    login: admin
    password: 123456
原文地址:https://www.cnblogs.com/liujitao79/p/4661964.html