Python讀取YAML配置檔案【簡易版】
阿新 • • 發佈:2021-07-25
自動化測試過程中,引數配置可以放在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)))}