zoukankan      html  css  js  c++  java
  • python 参数化之读取写入yaml文件

    最近自动化测试参数化使用了yaml文件进行存放,简单记录读取和写入操作

    1.读取如下yaml文件中的具体value值代码如下

    #测试环境IP、端口
    host: localhost:8080
    
    ---
    #仿真环境IP、端口
    host: localhost:8081
    def filePath(fileDir, fileName):
        return os.path.join(
            os.path.dirname(os.path.dirname(__file__)), fileDir, fileName)
    
    def readYaml(filePath):
        with open(filePath, 'r', encoding='utf-8') as f:
            return list(yaml.safe_load_all(f))
    
    fileDir = 'config'
    file = 'config.yaml'
    data = readYaml(filePath(fileDir, file))
    print(data[0]['host'])  # 打印结果为:localhost:8080

    2.写入操作,常用作上个操作返回的值将其写入yaml文件,供后面操作读取使用,yaml文件及参考代码如下:

    def set_state(docNumber, key, value):
        file_name = "test.yaml"
        with open(file_name, 'r', encoding="utf-8") as f:
            doc = list(yaml.safe_load_all(f))  # 将类型转换为list类型
            # print(list(doc))
        doc[docNumber][key] = value
        with open(file_name, 'w', encoding="utf-8") as f:
            yaml.safe_dump_all(doc, f, default_flow_style=False)
    
    set_state(value='http://122.123.124.125:8888',
              docNumber=1,
              key='host')    

    执行后的结果为:

    host: localhost:8080
    
    ---
    host: http://122.123.124.125:8888

    注意:yaml文档由“---”分隔,如果任何流(例如文件)包含多个文档,则应使用yaml.safe_load_all函数,而不是yaml.safe_load;

    写入非“---”分隔的文档时,使用yaml.safe_load、yaml.safe_dump即可,同时不需要转换类型;参考代码如下:

    def set_state(key, value):
        file_name = "test.yaml"
        with open(file_name, 'r', encoding="utf-8") as f:
            doc = yaml.safe_load(f)
    
        doc[key] = value
        with open(file_name, 'w', encoding="utf-8") as f:
            yaml.safe_dump(doc, f, default_flow_style=False)
  • 相关阅读:
    Linux _条件变量
    Linux _pthread 线程的同步 浅见
    Linux pthread 线程 浅解
    Linux _守护进程 浅解
    Linux _孤儿进程和僵尸进程 浅见
    Linux 小技巧
    Linux _sem 信号量 V_P
    树莓派ZeroW上传数据文件到阿里云对象存储OSS(Python)
    树莓派ZeroW开机自动运行
    树莓派ZeroW串口通讯
  • 原文地址:https://www.cnblogs.com/jiahm/p/13811218.html
Copyright © 2011-2022 走看看