当需要获取yaml文件格式的配置时,需要进行解析
pip3 install pyyaml
import yaml
with open(filename, encoding='utf-8') as fr:
yaml.safe_load(fr)
注:由于yaml.load()支持原生Python对象,不安全,建议使用yaml.safe_load()
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}
]# 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]]}
]# 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