1. 程式人生 > >內置模塊之configparser

內置模塊之configparser

ini文件 line option conf ems 打印 light 鍵值對 highlight

configparser模塊

  configparser模塊用來操作配置文件(.ini格式),這種格式的配置文件,包含多個組section,每個組可以包含多個鍵值對option,目前.ini這種格式的配置文件已經逐漸的不流行了。

  ##############################################

  配置文件的思想:

   # 當你把你本機的整個程序都拷貝到其他機器上,無論相對路徑/相對路徑都不靠譜,因為別的機器上的環境不一定與你的開發環境一直,然後其他操作人員又不一定懂開發,此時就需要配置文件了,把這些都放在一個配置文件中,讓其他人員也能修改,從而保證程序的正常運行。

  ##############################################

  configparser:

    (1) 格式約束十分嚴格,必須把配置項都放置到一個section中,忽略大小寫。

    (2) DEFAULT組是一個十分特殊的組,它屬於所有組,在其他組裏面都可以覆蓋其配置項,也可以在其他組裏取到DEFAULT的任何一個配置項。類似於父類與子類的感覺。


configparser模塊的使用

  下面有一個現成的.ini格式的配置文件:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

  如何使用configeparser模塊生成一個這樣的.ini文件

import configparser
#(1) 實例化得到一個config對象
config = configparser.ConfigParser()
#(2)對象[section名] = {key1:value1,key2:value2}進行在section中添加section
config[‘DEFAULT‘] = {
    ‘ServerAliveInterval‘: ‘45‘,
    ‘Compression‘: ‘yes‘,
}

config[‘bitbucket.org‘] = {
    ‘User‘:‘hg‘
}

config[‘topsecret.server.com‘] = {
    ‘Host Port‘: ‘50022‘,
    ‘password‘ : ‘xxxxx‘
}
#(3)打開一個配置文件,把內容寫入。
with open(‘config.ini‘,‘w‘) as f: config.write(f)

  學會了生成配置文件,那麽該如何查找配置文件的option。

#(1)先實例化出來一個對象
config = configparser.ConfigParser()

# (2)把配置文件中的所有內存讀進來
config.read(‘config.ini‘)

#(3)基於字典的形式查詢
print(config[‘topsecret.server.com‘][‘Host Port‘])
>>>
50022

# (4) 在任意一個組都可以查詢到DEFAULT組的任意option
print(config[‘topsecret.server.com‘][‘compression‘])
>>>
yes

#(5) 既然是基於字典的形式,那麽肯定也可以通過for循環來查詢
# 默認都會把DEFAULT組中的所有key都打印出來
for key in config[‘topsecret.server.com‘]:
    print(key)
>>>
host port
password
serveraliveinterval
compression

#(6)獲取組下面的鍵值對,通過"對象名.items(‘section‘)"
print(config.items(‘topsecret.server.com‘))
>>>
[(‘serveraliveinterval‘, ‘45‘), (‘compression‘, ‘yes‘), (‘host port‘, ‘50022‘), 
(‘password‘, ‘xxxxx‘)]

  學會了創建,查詢,接下來學習如果增刪改配置項

# 增刪改
config = configparser.ConfigParser()

config.read(‘config.ini‘)

# 增加section
config.add_section(‘mysection‘)
# 刪除原有section
config.remove_section(‘bitbucket.org‘)

# 在section中增加新的option
config[‘mysection‘][‘name‘] = ‘hehehe‘
# 在section中刪除option
config.remove_option(‘topsecret.server.com‘,‘password‘)

#更改option
config.set(‘topsecret.server.com‘,‘host port‘,‘8086‘)

#保存文件
config.write(open(‘new_config.ini‘,‘w‘))

  

內置模塊之configparser