此模塊提供了一個實現基本配置語言的類
首先來看一個非常基本的配置文件,如下所示格式:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
可以通過編程的方式創建上述文件:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
>>> config['bitbucket.org'] = {}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = {}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022' # mutates the parser
>>> topsecret['ForwardX11'] = 'no' # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
... config.write(configfile)
...
創建完畢之后我們可以通過以下代碼來回讀所記錄的數據:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key) # 默認值會一直存在
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
配置文件有幾個部分組成:每個部分有[section]標題引導,其后跟着特定的字符串(=或:)分割鍵值對。默認情況下,節名稱區分大小寫。值可以跨越多行,只要他們比第一行縮進更深。
配置文件可以包括注釋,通過特定的字符(#或;)表示。
例如:
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true
[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day
[No Values]
key_without_value
empty string value here =
[You can use comments]
# like this
; or this
# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.
[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?
由於解析器並不會記錄文件中值得數據類型,它始終以字符串的形式保存。因此簡單的傳遞 bool() 函數並不會處理出正確結果,因為 bool('False') 仍然返回 True 配置器提供了一個方法 ** getboolean()** 此方法可以識別 (不區分大小寫)'yes'/ 'no','on'/ 'off', 'true'/ 'false'和'1'/ '0'中的布爾值。例如: ```python # 上接上述配置代碼 >>> topsecret.getboolean('ForwardX11') False >>> config['bitbucket.org'].getboolean('ForwardX11') True >>> config.getboolean('bitbucket.org', 'Compression') True # 此外,配置器還提供了 getint() 和 getfloat() 方法來處理數據類型 ```
像字典一樣,配置器提供了獲取 section 值的方法 get()
>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
需要注意的是:默認值(default)優先於回退值(fallback),例如CompressionLevel
密鑰僅在該DEFAULT
部分中指定。如果我們嘗試topsecret.server.com
部分獲取它,即使我們指定了后備,我們也將始終獲得默認值
>>> topsecret.get('CompressionLevel', '3')
'9'
以下是 configparser 模塊的基本方法: * 讀取配置文件 1. defaults() 返回包含實例范圍默認值的字典 2. read(filename) 直接讀取ini文件內容 3. sections() 獲取所有的 section,以列表的形式返回 4. options(section) 獲取指定 section 的所有的 option 5. items(section) 獲取指定 section 所有的鍵值對 6. get(section, option) 獲取指定 section 中 option 的值 7. getint(section, option) 獲取指定 section 中 option 的值,以 int 類型返回 8. getfloat(section, option) 獲取指定 section 中 option 的值,以 float 類型返回 9. getboolean(section, option) 獲取指定section 中 option 的值,以 boolean類型返回 * 寫入配置文件 1. add_section(section) 添加指定的新的 section 2. has_section(section) 判斷是否存在指定的 section 3. set(section, option, value) 設置指定 section 中 option 的值 4. remove_section(section) 刪除指定 section 5. remove_option(section, option) 刪除指定 section 中的 option 6. write(fileobject) 將內容寫入配置文件