zoukankan      html  css  js  c++  java
  • 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

    ~~~

  • 相关阅读:
    计算机专业术语中英对照
    PhpStorm如何下载github上的代码到本地
    PDO学习
    Shell中特殊的变量
    Shell中变量的使用
    修改cmd的字体
    Shell的输入输出
    Shell入门第一课
    设计模式--观察者(Observer)
    eclipse中使用git提交代码到github
  • 原文地址:https://www.cnblogs.com/paulwhw/p/12297056.html
Copyright © 2011-2022 走看看