python常用模块——configparser,,常用模块 confi


常用模块 configparser

该模块是处理配置文件的模块。配置文件内如下格式:

[info]key = value

一、 方法

这里我们主要讲对象的方法。configparser模块的ConfigParser方法的子方法;

我们先得到对象 config:

import configparserconfig = configparser.ConfigParser()

下面我们是围绕这个对象config进行操作,对配置文件的增删改查;

1. sections()

返回配置文件的所有section名字,除了DEFAULT.

2. has_section(section)

返回一个布尔值,判断配置文件中是否有该section。

3. has_option(section, option)

返回一个布尔值,判断配置文件中是否有指定section下的option。

4. options(section)

返回配置文件中指定的section下option的一个列表;除了指定的section在内外,还会自动加上 DEFAULT下的option;

5. read(filenames, encoding=None)

 读取配置文件的内容到对象;

6. read_file(f, filename=None)

读取配置文件的内容到对象;这里的f是一个文件的句柄;例如:    import configparser    config = configparser.ConfigParser()    f=open(‘example.ini‘)    config.read_file(f)               # 这两句等效 config.read(‘example.ini‘)

7. read_string(string)

从指定的字符串中读取配置到对象;

8. read_dict(dictionary)

从指定的字典读取配置到对象;字典的key为section的名字,value为字典形式,即option和值;

9. get(section, option, raw=False, vars=None, fallback=_UNSET)

返回指定section、option对应的值;

10. getint(section, options, raw=False, vars=None, fallback=_UNSET)

类似get方法,但是将值转换为一个整数;

11. getfloat(section, options, raw=False, vars=None, fallback=_UNSET)

类似get方法,但是将值转换为一个浮点数;

12. getboolean(section, options, raw=False, vars=None, fallback=_UNSET)

类似get方法,但是将值转换为一个布尔值;当前是 0, false, no, off 的都会转换为 False;当前值是 1, true, yes, on 的都会转换为 True. 

13. items(section=_UNSET, raw=False, vars=None)

如果指定了section,则返回指定section的option和值;同时也附带DEFAULT下面option和值;返回的是一个列表嵌套元组的形式;例如:    import configparser    config = configparser.ConfigParser()    config.read(‘example.ini‘)    print(config.items(‘vxlan‘))          # 返回 [(‘key‘, ‘value‘), (‘enable_vxlan‘, ‘False‘)]

14. remove_section(section)

删除指定的section及它下面的所有options;

15. remove_option(section, option)

删除指定的section的option;

16. set(section, option, value)

添加/设置指定的section下option;

17. write(fp, spacearounddelimiters=True)

将对象写入指定的文件fp中;例如:    with open(‘example.ini‘, ‘w‘) as configfile:        config.write(configfile)            # config为上面提到的对象,贯穿整个操作; 

二、 案例

下面以openstack的 /etc/neutron/plugins/ml2/linuxbridge_agent.ini 为例; 该配置文件如下:

#  cat /etc/neutron/plugins/ml2/linuxbridge_agent.ini    [DEFAULT]    key=value                       # 该项是我加的,因为DEFAULT下没有;    [agent]    [linux_bridge]    physical_interface_mappings = provider:eth0    [securitygroup]    enable_security_group = True    firewall_driver = neutron.agent.linux.iptables_firewall.IptablesFirewallDriver    [vxlan]    enable_vxlan = False

1. 创建一个类似的配置文件

    import configparser          config = configparser.ConfigParser()         # 得到对象 config;        config["DEFAULT"] = {"key":"value"}    config["agent"] = {}    config["linux_bridge"] = {"physical_interface_mappings":"provider:eth0"}    config["securitygroup"] = {"enable_security_group":"True","firewall_driver":"neutron.agent.linux.iptables_firewall.IptablesFirewallDriver"}    config["vxlan"] = {"enable_vxlan":"False"}            with open(‘example.ini‘, ‘w‘) as configfile:       config.write(configfile)

2. 配置的增删改查

    import configparser        config = configparser.ConfigParser()         # 生成一个对象,接下来我们都是围绕这个对象操作;        #################### 查询    print(config.sections())    # 输出[]  说明现在还是一个空对象        config.read(‘example.ini‘) # 让这个对象读配置文件        print(config.sections())    # 打印这个对象的sections;注意,DEFAULT是特殊的,不打印;   输出[‘agent‘,‘linux_bridge‘,‘securitygroup‘,‘vxlan‘]        print(‘bashrunning.com‘ in config) # 关系测试  返回布尔值False        print(config[‘vxlan‘][‘enable_vxlan‘])  # 输出值‘False‘        print(config[‘DEFAULT‘][‘key‘])  # 返回 value                    for key in config[‘securitygroup‘]:        print(key)                              # 输出:‘key‘ ‘enable_security_group‘ ‘firewall_driver‘ 三行;打印sections时,会把 DEFAULT的option一并打印;        for key in config[‘DEFAULT‘]:        print(key)                              #输出 key            print(config.options(‘vxlan‘))# [‘key‘, ‘enable_vxlan‘]  附带 DEFAULT的option    print(config.items(‘vxlan‘))  #[(‘key‘, ‘value‘), (‘enable_vxlan‘, ‘False‘)] 附带DEFAULT的option和值        print(config.get(‘vxlan‘,‘enable_vxlan‘))# 返回enable_vxlan的值 False    #################### 增删改    config.add_section(‘info‘)                      # 增加section        config.remove_section(‘vxlan‘)                  # 删除section    config.remove_option(‘vxlan‘,‘enable_vxlan‘)    # 删除option        config.set(‘info‘,‘www‘,‘www.bashrunning.com‘)  # 增加option和值        #################### 写入配置文件    config.write(open(‘mypython.cfg‘, "w"))         # 将对象config的内容写入mypython.cfg文件 

python常用模块——configparser

评论关闭