前言
当需要获取yaml文件格式的配置时,需要进行解析
使用说明
安装包pyyaml
pip3 install pyyaml
导入包yaml
import yaml
用法
- yaml.safe_load(yaml字符串或文件句柄),转换成字典格式,如果yaml中有中文,需要转换为utf-8格式,字符串为:str.encode(‘utf-8′),文件句柄则为:
with open(filename, encoding='utf-8') as fr:
yaml.safe_load(fr)
注:由于yaml.load()支持原生Python对象,不安全,建议使用yaml.safe_load()
示例
- yaml.safe_load(yaml字符串)
yaml字符串如下所示
yaml_str = '''
name: Cactus
age: 18
skills:
-
- Python
- 3
-
- Java
- 5
has_blog: true
gf: ~
'''
python终端输出,如下所示:
]# python3
>>> import yaml
>>> yaml_str = '''
... name: Cactus
... age: 18
... skills:
... -
... - Python
... - 3
... -
... - Java
... - 5
... has_blog: true
... gf: ~
... '''
>>> print(yaml.safe_load(yaml_str))
{'name': 'Cactus', 'age': 18, 'skills': [['Python', 3], ['Java', 5]], 'has_blog': True, 'gf': None}
- yaml.safe_load(文件句柄)
]# cat test.yaml
age: 18
gf: null
has_blog: true
name: Cactus
skills:
- - Python
- 3
- - Java
- 5
]# cat > test.py <<-EOF
import yaml
with open("test.yaml", encoding='utf-8') as fr:
print(yaml.safe_load(fr))
EOF
]# python3 test.py
{'age': 18, 'gf': None, 'has_blog': True, 'name': 'Cactus', 'skills': [['Python', 3], ['Java', 5]]}
- yaml.dump(dict):默认为flow流格式,即字典{b’: {‘c’: 3, ‘d’: 4}},会被转为b: {c: 3, d: 4}形式,可以使用default_flow_style=False关闭流模式
示例
]# cat > test.py <<-EOF
import yaml
yaml_dict = {'name': 'Cactus', 'age': 18, 'skills': [['Python', 3], ['Java', 5]], 'has_blog': True, 'gf': None}
with open('test.yaml', 'w', encoding='utf-8') as fw:
yaml.dump(yaml_dict, fw, default_flow_style=False) # 写入文件,不是用flow流格式,默认为flow流格式
EOF
]# python3 test.py
]# cat test.yaml
age: 18
gf: null
has_blog: true
name: Cactus
skills:
- - Python
- 3
- - Java
- 5
结语
PyYAML 文档
app.yaml 参考文档
Python Yaml
YAML Example Configurations