Python自动化运维📒Python实用笔记

YAML语法简介

2017-02-13  本文已影响119人  极地瑞雪

YAML的数据结构

YAML的设计者认为在配置文件中所要表达的数据内容有三种类型

Sequence of Scalars

YAML(ball players)

- Mark McGwire
- Sammy Sosa
- Ken Griffey

Python(YAML)

['Mark McGwire', 'Sammy Sosa', 'Ken Griffey']

Mapping Scalars to Scalars

YAML(player statistics)

hr:  65    # Home runs
avg: 0.278 # Batting average
rbi: 147   # Runs Batted In

Pyhton(YAML)

{'hr':65, 'avg':0.278, 'rbi':147}

Mapping Scalars to Sequences

YAML(ball clubs in each league)

american:
  - Boston Red Sox
  - Detroit Tigers
  - New York Yankees
national:
  - New York Mets
  - Chicago Cubs
  - Atlanta Braves

Python(YAML)

{'american':['Boston Red Sox', 'Detroit Tigers', 'New York Yankees'], 'national':['New York Mets', 'Chicago Cubs', 'Atlanta Braves']}

Sequence of Mappings

YAML(players’ statistics)

-
  name: Mark McGwire
  hr:   65
  avg:  0.278
-
  name: Sammy Sosa
  hr:   63
  avg:  0.288

Python(YAML)

[{'name':'Mark McGwire', 'hr':65, 'avg':0.278}, {'name':'Sammy Sosa', 'hr':63, 'avg':0.288}]

Sequence of Sequences

YAML

- [name        , hr, avg  ]
- [Mark McGwire, 65, 0.278]
- [Sammy Sosa  , 63, 0.288]

Python(YAML)

[['name', 'hr', 'avg'], ['Mark McGwire', 65, 0.278], ['Sammy Sosa', 63, 0.288]]

Mapping of Mappings

YAML

Mark McGwire: {hr: 65, avg: 0.278}
Sammy Sosa: {
    hr: 63,
    avg: 0.288
  }

Python(YAML)

{'Mark McGwire':{'hr':65, 'avg':0.278}, 'Sammy Sosa':{'hr':63, 'avg':0.288}}

YAML中的注释

YAML

#ball players
- Mark McGwire
- Sammy Sosa
- Ken Griffey

YAML中的文档

在单一一个YAML文件中

YAML(Two Documents in a Stream)

# Ranking of 1998 home runs
---
- Mark McGwire
- Sammy Sosa
- Ken Griffey
 
# Team ranking
---
- Chicago Cubs
- St Louis Cardinals

YAML

---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...

实例

YAML

用YAML来描述一本书《Linux命令行与shell脚本编程大全》
 
# 《Linux命令行与shell脚本编程大全》描述
---  # begin of document
书名: 'Linux命令行与shell脚本编程大全'
出版社: '人民邮电出版社'
原作者: ['Richard Blum', 'Christine Bresnahan']
译者:
    - 武海峰
    - 朱巍
前二章节:
    - 第一章: 初识Linux Shell
    - 第二章: 走进Shell
 
#end of document

Python(YAML)

{'书名':'Linux命令行与shell脚本编程大全', '出版社':'人民邮电出版社', '原作者':['Richard Blum', 'Christine Bresnahan'], '译者':['武海峰', '朱巍'], '前二章节':{'第一章':'初识Linux Shell', '第二章':'走进Shell'}}

参考文档:

上一篇 下一篇

猜你喜欢

热点阅读