python經常使用模塊——configparser

經常使用模塊 configparser

該模塊是處理配置文件的模塊。配置文件內以下格式:python

[info]
key = value

1、 方法

這裏咱們主要講對象的方法。configparser模塊的ConfigParser方法的子方法;linux

咱們先獲得對象 config:web

import configparser
config = configparser.ConfigParser()

下面咱們是圍繞這個對象config進行操做,對配置文件的增刪改查;bash

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爲上面提到的對象,貫穿整個操做;

2、 案例

下面以openstack的 /etc/neutron/plugins/ml2/linuxbridge_agent.ini 爲例; 該配置文件以下:app

#  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文件 
相關文章
相關標籤/搜索