Fork me on GitHub

Python读取YAML文件

介绍如何使用Python读取YAML文件

前言

越来越多的项目使用YAML格式的文件作为配置文件或者数据文件,例如:Docker、Ansible PlayBook,SaltStack state文件等等。今天专门研究了一下,记录于此。

适用场景

  • 脚本语言

    由于实现简单,解析成本很低,YAML特别适合在脚本语言中使用。列一下现有的语言实现:Ruby,Java,Perl,Python,PHP,OCaml,JavaScript,Go 除了Java 和 Go,其他都是脚本语言。

  • 序列化

    YAML比较适合做序列化。因为它是宿主语言数据类型直转的。

  • 配置文件

    YAML做配置文件也不错。写YAML要比写XML快得多(无需关注标签或引号),并且比ini文档功能更强。比如Ruby on Rails的配置就选用的YAML。对ROR而言,这很自然,也很省事.由于兼容性问题,不同语言间的数据流转建议不要用YAML.

PyYAML库

Python官网说明

安装

1
2
3
# yum install -y python-pip
# pip install --upgrade pip
# pip install PyYAML

应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[root@linux-node7 ~]# cat docker-compose-consul.yml
# backend web application, scale this with docker-compose scale web=3
web:
image: yeasy/simple-web:latest
environment:
SERVICE_80_NAME: http
SERVICE_NAME: web
SERVICE_TAGS: backend
ports:
- "80"

# load balancer will automatically update the config using consul-template
lb:
image: yeasy/nginx-consul-template:latest
hostname: lb
links:
- consulserver:consul
ports:
- "80:80"

consulserver:
image: gliderlabs/consul-server:latest
hostname: consulserver
ports:
- "8300"
- "8400"
- "8500:8500"
- "53"
command: -data-dir /tmp/consul -bootstrap -client 0.0.0.0

# listen on local docker sock to register the container with public ports to the consul service
registrator:
image: gliderlabs/registrator:master
hostname: registrator
links:
- consulserver:consul
volumes:
- "/var/run/docker.sock:/tmp/docker.sock"
command: -internal consul://consul:8500
# command: consul://consul:8500
1
2
3
4
5
6
7
8
[root@linux-node7 ~]# cat read_xml.py
import yaml

f = open("docker-compose-consul.yml")
yaml_context = yaml.load(f)
print yaml_context
[root@linux-node7 ~]# python read_xml.py
{'web': {'environment': {'SERVICE_80_NAME': 'http', 'SERVICE_TAGS': 'backend', 'SERVICE_NAME': 'web'}, 'image': 'yeasy/simple-web:latest', 'ports': ['80']}, 'registrator': {'image': 'gliderlabs/registrator:master', 'hostname': 'registrator', 'command': '-internal consul://consul:8500', 'links': ['consulserver:consul'], 'volumes': ['/var/run/docker.sock:/tmp/docker.sock']}, 'lb': {'image': 'yeasy/nginx-consul-template:latest', 'hostname': 'lb', 'ports': ['80:80'], 'links': ['consulserver:consul']}, 'consulserver': {'image': 'gliderlabs/consul-server:latest', 'hostname': 'consulserver', 'command': '-data-dir /tmp/consul -bootstrap -client 0.0.0.0', 'ports': ['8300', '8400', '8500:8500', '53']}}

找工具解析下结果 https://www.bejson.com/jsonviewernew/

1
2
说明:
# 注释的部分解析时自动忽略

参考资料

Python官网PyYAML说明

======================================================
希望各位朋友支持一下

本文作者:dongsheng
本文地址https://mds1455975151.github.io/archives/326bf63c.html
版权声明:转载请注明出处!

坚持技术分享,您的支持将鼓励我继续创作!