1. 程式人生 > >python常用模組——configparser

python常用模組——configparser

常用模組 configparser

該模組是處理配置檔案的模組。配置檔案內如下格式:

[info]
key = value

一、 方法

這裡我們主要講物件的方法。configparser模組的ConfigParser方法的子方法;

我們先得到物件 config:

import configparser
config = 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檔案