python 程序 读取,yml 文件 作为配置文件

安装python yml 插件

pip install pyyaml -i https://mirrors.ustc.edu.cn/pypi/web/simple/

编写配置文件 config.yaml

ip: 127.0.0.1
port: 5003
appKey: 32b2f148-a0c7-40ef-a7e2-5c25fa23b702

程序读取配置

import yaml

yamlPath = 'config.yaml'

config = [];
#读取配置文件
def loadConfig():
    with open(yamlPath,'rb') as f:
        # yaml文件通过---分节,多个节组合成一个列表
        date = yaml.safe_load_all(f)
        # salf_load_all方法得到的是一个迭代器,需要使用list()方法转换为列表
        config=(list(date));
        return config;
#从配置文件获得指定key的值
def getConfig(key):
    config=loadConfig()
    for item in config: 
        if not item[key] is None:
            return item[key];

#调用
port=getConfig("port");

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章