涛子 - 简单就是美

成单纯魁增,永继振国兴,克复宗清政,广开家必升

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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, bandwidth: 300}
- {ip: 192.168.2.100, name: sh, port: Port-channel 4, community: passwd, bandwidth: 1000}
- {ip: 192.168.1.100, name: bj, port: GigabitEthernet 0/48, community: passwd, bandwidth: 10000}
web: {login: admin, password: 123456}
interval: 60
switch:
-   ip: 192.168.3.100
    name: gz
    port: Port-channel 1
    community: passwd
    bandwidth: 300
-   ip: 192.168.2.100
    name: sh
    port: Port-channel 4
    community: passwd
    bandwidth: 1000
-   ip: 192.168.1.100
    name: bj
    port: GigabitEthernet 0/48
    community: passwd
    bandwidth: 10000
web:
    login: admin
    password: 123456
posted on 2015-07-20 17:05  北京涛子  阅读(414)  评论(0编辑  收藏  举报