Python项目获取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=config["MYSQL"]["PORT"],
    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

~~~

猜你喜欢

转载自www.cnblogs.com/paulwhw/p/12297056.html