configparser模块获取settings.ini文件中的配置数据

测试项目的目录如下:

其中settings.ini中存放着配置数据;conf.py脚本中是获取配置数据的逻辑;method.py脚本中导入配置信息:

settings.ini内容如下:

[REDIS]
HOST = 127.0.0.1
PORT = 6379
USER = test

[MYSQL]
HOST = 127.0.0.1
PORT = 3306
USER = whw

conf.py内容如下:

import os
import configparser

current_path = os.path.abspath(".")
config = configparser.ConfigParser()
config.read(os.path.join(current_path,"settings.ini"))

redis_conf = dict(
    host=config["REDIS"]["HOST"],
    port=config["REDIS"]["PORT"],
    user=config["REDIS"]["USER"],
    )

mysql_conf = dict(
    host=config["MYSQL"]["HOST"],
    port=int(config["MYSQL"]["PORT"]), # 注意这里得把port转换成int!
    user=config["MYSQL"]["USER"],
    )


if __name__ == '__main__':
    print(redis_conf) # {'host': '127.0.0.1', 'port': '6379', 'user': 'test'}
    print(mysql_conf) # {'host': '127.0.0.1', 'port': '3306', 'user': 'whw'}

method.py内容如下:

from conf import redis_conf,mysql_conf


if __name__ == '__main__':
    print(redis_conf["user"]) # test
    print(mysql_conf["user"]) # whw

~~~

 

posted on 2020-02-11 22:09  江湖乄夜雨  阅读(459)  评论(0编辑  收藏  举报