python 读取配置文件,加载到程序中

system.yaml配置文件的内容:

stage1:
  number_of_shards: 3 # 命中次数
  file_size: 600 # 字节
stage2:
  is_rows: True # 是否需要limit
  rows: 6000 # limit行数
loggfile: "loggle.log"

方法一 使用yaml包,实现“字典”方式配置参数

import os
import yaml


def test_yaml():
    filepath = os.path.join(os.getcwd(), './dbUntils/system.yaml')  # 文件路径,这里需要将a.yaml文件与本程序文件放在同级目录下
    with open(filepath, 'r', encoding='UTF-8') as f:  # 用with读取文件更好
        configs = yaml.load(f, Loader=yaml.FullLoader)  # 按字典格式读取并返回
    # 显示读取后的内容
    print(type(configs))  # <class 'dict'>
    print(configs["stage1"])  # {'number': 3, 'banchsize': 32}
    print(configs["stage1"]['number_of_shards'])  # 3
    print(configs['loggfile'])  # loggle.log
    return configs


if __name__ == "__main__":
    test_yaml()

方法二:使用yaml+argparse+命名空间,实现“命名空间”方式配置参数
参看这边大佬的文章
我觉得第一种就已经够我使用了

posted @ 2022-05-07 00:16  darling331  阅读(100)  评论(0编辑  收藏  举报