yaml
程序中经常涉及一些配置,yaml是比较常用的工具,汇总一下常见的写法。
# [YAML | In One Video](https://www.youtube.com/watch?v=cdLNKUoMc6c)
name: &name "mike" # anchor
occupation: "programmer"
age: !!float 23 # int casted into float
gpa: 3.5 # flaot
fav_num: 1e+10
male: true # boolean
birthday: 1994-02-06 12:33:22 # ISO 8601
flaws: null # null
hobbies:
- hiking
- movies
- riding bike
movies: ['Dark Knight', 'Good Will Hunting'] # list
friends: # objects list
- name: "Steph"
age: 22
- {name: "Adam", age: 22}
-
name: "Joe"
age: 23
desc: >
Line 1
Line 2
Line 3
signature:
Mike
Giraffe Achademy
email - mike@gmail.com
id: *name # value of mike
用python解析(成字典)也相对简单:
import yaml
with open('config.yaml', 'r') as fr:
cfg = yaml.safe_load(fr)
print(cfg)
输出结果
{'flaws': None, 'name': 'mike', 'occupation': 'programmer', 'age': 23.0, 'hobbies': ['hiking', 'movies', 'riding bike'], 'gpa': 3.5, 'fav_num': '1e+10', 'movies': ['Dark Knight', 'Good Will Hunting'], 'birthday': datetime.datetime(1994, 2, 6, 12, 33, 22), 'signature': 'Mike Giraffe Achademy email - mike@gmail.com', 'male': True, 'friends': [{'age': 22, 'name': 'Steph'}, {'age': 22, 'name': 'Adam'}, {'age': 23, 'name': 'Joe'}], 'id': 'mike', 'desc': 'Line 1 Line 2 Line 3\n'}