Python读取YAML配置文件【简易版】

自动化测试过程中,参数配置可以放在YMAL文件管理,以list或者dict数据格式存放参数,Python脚本能够方便读取YAML文件内容。

 

Python package安装:

pip install PyYAML

 

举例如下:

YAML配置文件,test_data.yml

-
  username: 'user01'
  password: '123456'
-
  username: 'user02'
  password: '000000'

 

测试脚本文件,test.py

import yaml


def yaml_load(file):
    with open(file, mode='r', encoding='utf-8') as fd:
        data = yaml.load(fd, Loader=yaml.FullLoader)
    return data


if __name__ == '__main__':
    file = 'test_data.yml'
    data = yaml_load(file)
    print(type(data), data)

 

脚本运行结果:

<class 'list'> [{'username': 'user01', 'password': '123456'}, {'username': 'user02', 'password': '000000'}]

 

关于YAML文件数据格式,可以使用string int float boolean date datetime等数据格式。

如下YAML内容:

string: 'hello world'
int:
  - +100
  - -100
float:
  - 3.141592653
  - -0.01
boolen:
  - true
  - False
  - null
  - ~
date: 2021-12-31
datetime: 2021-12-31T10:10:10+08:00 # notes, datetime format

Python脚本读取结果:

<class 'dict'> {'string': 'hello world', 'int': [100, -100], 'float': [3.141592653, -0.01], 'boolen': [True, False, None, None], 'date': datetime.date(2021, 12, 31), 'datetime': datetime.datetime(2021, 12, 31, 10, 10, 10, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800)))}

posted on 2021-07-25 11:06  Zhangwill  阅读(254)  评论(0编辑  收藏  举报

导航