pyyaml模块是一种文件数据处理格式的方法,常用与生成、解析或修改.yaml配置文件
1.常见.yaml文件格式内容如下
languages:
- Ruby
- Perl
- Python
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org
2.pyyaml模块的简单使用
# -*- coding:utf-8 -*- # Author:Wong Du ''' 以下是pyyaml模块的简单用法, 详细请见:https://pyyaml.org/wiki/PyYAMLDocumentation ''' import yaml ### Part1 print(yaml.load(""" - wong - dudu - caiyun """)) # 效果:['wong', 'dudu', 'caiyun'] ### Part2 a = yaml.load(""" name: wong: age: 24 dudu: age: 23 """) print(a) # 效果:{'name': {'dudu': {'age': 23}, 'wong': {'age': 24}}} ### Part3 # '---'作为分隔符分隔多个字典,加载documents内的三个dict documents = """ --- name: The Set of Gauntlets 'Pauraegen' description: A set of handgear with sparks that crackle across its knuckleguards. --- name: The Set of Gauntlets 'Paurnen' description: A set of gauntlets that gives off a foul, acrid odour yet remains untarnished. --- name: The Set of Gauntlets 'Paurnimmen' description: A set of handgear, freezing with unnatural cold. """ # 解析多个字典,要用load_all,解析documents内容生成一个生成器 b = yaml.load_all(documents) b_data_list = [] for data in b: print(data) b_data_list.append(data) ''' 效果: {'name': "The Set of Gauntlets 'Pauraegen'", 'description': 'A set of handgear with sparks that crackle across its knuckleguards.'} {'name': "The Set of Gauntlets 'Paurnen'", 'description': 'A set of gauntlets that gives off a foul, acrid odour yet remains untarnished.'} {'name': "The Set of Gauntlets 'Paurnimmen'", 'description': 'A set of handgear, freezing with unnatural cold.'} ''' ### Part4 # 将多个字典转成字符串要用dump_all,生成yaml文档格式数据 c = yaml.dump_all(b_data_list, default_flow_style=False) print(c) with open('document.yaml', 'w') as f: f.write(c) # 写入 # 解析文件中的数据 with open('document.yaml') as f: d = yaml.load_all(f.read()) # 读取加载 print(d) # 生成器内存地址 for i in d: print(i) ### Part5 文档格式有不同表示方法,解析后效果相同 sum = """ a: 1 b: c: 3 d: 4 """ print(yaml.dump(yaml.load(sum))) ''' 效果: a: 1 b: {c: 3, d: 4} ''' print(yaml.dump(yaml.load(sum), default_flow_style=False)) ''' 效果: a: 1 b: c: 3 d: 4 '''
3.pyyaml模块解析文件小实例
apache:
pkg.installed: []
service.running:
- reload: True
- watch:
- file: /etc/httpd/conf/httpd.conf
user.present:
- uid: 87
- gid: 87
- home: /var/www/html
- shell: /bin/nologin
- require:
- group: apache
group.present:
- gid: 87
- require:
- pkg: apache
/etc/httpd/conf/httpd.conf:
file.managed:
- source: salt://apache/httpd.conf
- user: root
- group: root
- mode: 644
---
test:
- hostname
- ipaddr
- port
- operator
# -*- coding:utf-8 -*- # Author: Wongdu import yaml import os def host_parser(): path_file = 'host.yaml' data_list = [] if os.path.isfile(path_file): with open(path_file) as f: host_data = yaml.load_all(f.read()) for item in host_data: data_list.append(item) if len(data_list) > 1: data = data_list else: data = data_list[0] return data else: exit("%s is not a valid yaml config file.." % path_file) data = host_parser() print(data)