zoukankan      html  css  js  c++  java
  • python中configparser模块使用

    ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。 

    注意:在python 3 中ConfigParser模块名已更名为configparser

    configparser函数常用方法:

    读取配置文件:

     1 read(filename) #读取配置文件,直接读取ini文件内容
     2 
     3 sections() #获取ini文件内所有的section,以列表形式返回['log', 'mysql']
     4 
     5 options(sections) #获取指定sections下所有options ,以列表形式返回['host', 'port', 'user', 'password']
     6 
     7 items(sections) #获取指定section下所有的键值对,[('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
     8 
     9 get(section, option) #获取section中option的值,返回为string类型
    10 获取指定的section下的option <class 'str'> 127.0.0.1
    11 
    12 getint(section,option) 返回int类型
    13 getfloat(section, option)  返回float类型
    14 getboolean(section,option) 返回boolen类型

    举例如下:

    配置文件conf.ini内容如下:

    [log]
    name = demo
    level = INFO
    file_ok = True
    file_name = demo.log

    [mysql]
    host=127.0.0.1
    port=3306
    user=root
    password=123456

    注意,也可以使用:替换=

    代码如下:

    from configparser import ConfigParser

    # 实例化对象
    con = ConfigParser()
    con.read("conf.ini",encoding="utf-8")
    # 获取指定的section和option值
    val = con.get("log","name")
    print('获取指定的section下的option', type(val), val)

    # 获取所有section
    section = con.sections()
    print("获取配置文件所有的section",section)
    # 获取所有options
    option= con.options("mysql")
    print("获取配置文件所有的option",option)
    # 获取指定section下所有的键值对,返回的是一个列表
    item = con.items("mysql")
    print('获取指定section下所有的键值对', item)
    # 将列表转化成字典
    # item = dict(con.items("mysql"))
    # print(item["user"])

    # for key,val in item.items():
    # print(key,"=",val)

    运行结果如下:

      获取指定的section下的option <class 'str'> demo
      获取配置文件所有的section ['log', 'mysql']
      获取配置文件所有的option ['host', 'port', 'user', 'password']
      获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]

    综合使用方法:

    import configparser
    """
    读取配置文件信息
    """
    
    class ConfigParser():
    
        config_dic = {}
        @classmethod
        def get_config(cls, sector, item):
            value = None
            try:
                value = cls.config_dic[sector][item]
            except KeyError:
                cf = configparser.ConfigParser()
                cf.read('settings.ini', encoding='utf8')  #注意setting.ini配置文件的路径
                value = cf.get(sector, item)
                cls.config_dic = value
            finally:
                return value
    
    
    if __name__ == '__main__':
        con = ConfigParser()
        res = con.get_config('logging', 'level')
        print(res)

    参考链接:https://www.cnblogs.com/lhly/p/8066898.html

  • 相关阅读:
    623. Add One Row to Tree 将一行添加到树中
    771. Jewels and Stones 珠宝和石头
    216. Combination Sum III 组合总数三
    384. Shuffle an Array 随机播放一个数组
    382. Linked List Random Node 链接列表随机节点
    向github项目push代码后,Jenkins实现其自动构建
    centos下安装Jenkins
    python提取批量文件内的指定内容
    批处理实现:批量为文件添加注释
    python抓取每期双色球中奖号码,用于分析
  • 原文地址:https://www.cnblogs.com/tester-blog/p/14814105.html
Copyright © 2011-2022 走看看