Yaml是专门用来写配置文件的语言,非常简洁强大,比JSON格式方便。可用来做自动化测试框架的配置文件或用例文件
安装yaml:pip install PyYaml
#conf.yaml文件
username: user01
password: 123456
#py文件,读取yaml文件并转换成字典
import yaml
def get_yaml_data(filedir):
with open(filedir,'r',encoding='UTF-8') as file1:
res = yaml.load(file1,Loader=yaml.FullLoader)
print(res)
if __name__ == '__main__':
get_yaml_data('../configs/conf.yaml')
#执行结果:
{
'username': 'user01', 'password': 123456}
#conf.yaml文件
- 10
-
- 101
- 102
#执行结果:
[10, [101, 102]]
#conf.yaml文件
- 10
-
username: user01
password: 123456
#执行结果:
[10, {
'username': 'user01', 'password': 123456}]
#conf.yaml文件
username: user01
password: 123456
info:
- 101
- 102
#执行结果:
{
'username': 'user01', 'password': 123456, 'info': [101, 102]}
#conf.yaml文件
name: &user Marry
label1: *user
label2: *user
#执行结果:
{
'name': 'Marry', 'label1': 'Marry', 'label2': 'Marry'}
使用—作为分隔符
#conf.yaml文件
username: marry
password: 123456
---
- 101
- 102
- 103
import yaml
def get_yamls_data(filedir):
with open(filedir,'r',encoding='UTF-8') as file1:
resList = []
res = yaml.load_all(file1,Loader=yaml.FullLoader) #读多个yaml使用yaml.load_all
for one in res:
resList.append(one)
print(resList)
if __name__ == '__main__':
get_yamls_data('../configs/conf.yaml')
#a.yaml
username: marry
password: 123456
info: !include b.yaml # 继承b.yaml文件数据
#b.yaml
- 101
- 102
- 103
#继承yaml .py文件
import yaml
import os.path
class Loader(yaml.Loader):
def __init__(self,stream):
self.root = os.path.split(stream.name)[0]
super(Loader,self).__init__(stream)
def include(self,node):
filename = os.path.join(self.root,self.construct_scalar(node))
with open(filename,'r') as f:
return yaml.load(f,Loader)
Loader.add_constructor('!include',Loader.include)
if __name__ == '__main__':
with open('../configs/a.yaml') as f:
data = yaml.load(f,Loader)
print(data)
#执行结果:
{
'username': 'marry', 'password': 123456, 'info': [101, 102, 103]}