在Python使用yaml的几个例子

python版本:2.7.5

安装方法:pip install PyYaml


“把变量写进yaml做配置文件,然后python脚本从yaml文件里面取到变量”的方法最近是在python编程里比较流行的配置项方法。yaml更加易读,而且通过缩进表示结构,这一点与python不谋而合。


Yaml有四个比较常用的用法,分别是load()、dump()、load_all()、dump_all()。这篇文章主要就是了解一下这四个方法。


首先我们先写一个很简单的test.py:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import yaml

yaml_str = """
name: Gakki
age: 29
job: Actress
relationship: Wife
"""

aaa = yaml.load(yaml_str)
print aaa

执行的话,看到的效果就是:

[root@paas-online-crs-001 chentest]# python test.py 
{'job': 'Actress', 'age': 29, 'relationship': 'Wife', 'name': 'Gakki'}


这个aaa的类型是一个字典(dict),如果要得到里面那个"Gakki",那么就是aaa['name']。通过load方法,一个字符串变成了一个字典。


现在把test.py换成如下:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import yaml

yaml_dict = {"name": "Gakki",
         "age": 29,
         "job": "Actress",
         "relationship": "Wife"
              }
aaa = yaml.dump(yaml_dict, default_flow_style=False)
print aaa
print (type(aaa))

执行后的效果如下:

[root@paas-online-crs-001 chentest]# python test.py 
age: 29
job: Actress
name: Gakki
relationship: Wife
<type 'str'>


可见,通过dump方法,把一个dict变成了一个字符串。


现在写一个配置文件,假如它叫test.yaml:

- Gakki
- 29
- Actress
- Wife


再来一个test.py,内容如下: 

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import yaml

aaa = yaml.load(file('test.yaml', 'r'))
print aaa
print (type(aaa))

执行这个test.py:

[root@paas-online-crs-001 chentest]# python test.py 
['Gakki', 29, 'Actress', 'Wife']
<type 'list'>    #得到了一个列表


如果把那个test.yaml升级成字典和列表的混合结构,如下:

- name: Chris
  age: 29
  job: OM Engineer
- name: Gakki
  age: 29
  job: Actress
  relationship: Wife


执行test.py的效果如下:

[root@paas-online-crs-001 chentest]# python test.py 
[{'job': 'OM Engineer', 'age': 29, 'name': 'Chris'}, {'job': 'Actress', 'age': 29, 'relationship': 'Wife', 'name': 'Gakki'}]
<type 'list'>

既然获得的结果是一个包含字典的列表,那么如果要获得“Gakki”就是aaa[1]['name']


如果想要复制和引用,那么要用&和*,比如把test.yaml改成这样:

name: &name Gakki
wife: *name

执行test.py的效果如下:

[root@paas-online-crs-001 chentest]# python test.py 
{'name': 'Gakki', 'wife': 'Gakki'}
<type 'dict'>


在同一个yaml文件中,可以用 --- 来分段,这样可以将多个文档写在一个文件中:

---
  name: Chris
  age: 29
  job: OM Engineer
---
  name: Gakki
  age: 29
  job: Actress
  relationship: Wife

在写一个新的test.py如下: 

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import yaml
ys = yaml.load_all(file('gakki.yaml', 'r'))    #load_all() 方法会生成一个迭代器,可以用for输出出来
for y in ys:
    print y

执行这个py的效果:

[root@paas-online-crs-001 chentest]# python test.py 
{'job': 'OM Engineer', 'age': 29, 'name': 'Chris'}
{'job': 'Actress', 'age': 29, 'relationship': 'Wife', 'name': 'Gakki'}


参考文档:https://huilansame.github.io/huilansame.github.io/archivers/recommond-case-file-type-yaml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章