1.安装

pip3 install pyyaml

2.读取yaml 文件应用

yaml文件:

---
- username: user1
  password: psw1
- username: user2
  password: psw2
- username: user3
  password: psw3
- username: user4
  password: psw4
- username: user5
  password: psw5
...
---
- username: user6
  password: psw6
- username: user7
  password: psw7
- username: user8
  password: psw8
- username: user9
  password: psw9
- username: user10
  password: psw10
...

2.1 基本读取

import yaml

# 读取 YAML 文件
with open("config.yaml", "r", encoding="utf-8") as f:
    data = yaml.safe_load(f)   # 推荐 safe_load,避免安全问题
print(data)

2.2 读取多个文档

with open("multi_docs.yaml", "r", encoding="utf-8") as f:
    docs = list(yaml.safe_load_all(f))
print(docs)

3.yaml文件 变量的传递

yaml:

- method: post
  params:
    username: $user
    password: $psw
  url: http://127.0.0.1:8888/login

main.py:

import yaml
from string import Template
import os


def yaml_template(yamlPath,change_data):
    '''yaml的变量替换'''
    if not os.path.exists(yamlPath):
        raise FileNotFoundError("文件不存在")
    if not isinstance(change_data,dict):
        raise Exception("修改内容必须是字典!")
    with open(yamlPath,'r',encoding='utf-8') as f:
        cfg = f.read()
    content = Template(cfg).substitute(**change_data)
    return content

if __name__ == '__main__':
    change_data = {
        "user":"user01",
        "psw":"psw01",
    }
    res = yaml_template("./post_data.yaml",change_data)
    print(res)