configparser
--- 配置文件解析器?
源代碼: Lib/configparser.py
此模塊提供了它實(shí)現一種基本配置語(yǔ)言 ConfigParser
類(lèi),這種語(yǔ)言所提供的結構與 Microsoft Windows INI 文件的類(lèi)似。 你可以使用這種語(yǔ)言來(lái)編寫(xiě)能夠由最終用戶(hù)來(lái)自定義的 Python 程序。
備注
這個(gè)庫 并不 能夠解析或寫(xiě)入在 Windows Registry 擴展版本 INI 語(yǔ)法中所使用的值-類(lèi)型前綴。
參見(jiàn)
快速起步?
讓我們準備一個(gè)非?;镜呐渲梦募?,它看起來(lái)是這樣的:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
INI 文件的結構描述見(jiàn) 以下章節。 總的來(lái)說(shuō),這種文件由多個(gè)節組成,每個(gè)節包含多個(gè)帶有值的鍵。 configparser
類(lèi)可以讀取和寫(xiě)入這種文件。 讓我們先通過(guò)程序方式來(lái)創(chuàng )建上述的配置文件。
>>> 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)
...
如你所見(jiàn),我們可以把配置解析器當作一個(gè)字典來(lái)處理。 兩者確實(shí)存在差異,將在后文說(shuō)明,但是其行為非常接近于字典所具有一般行為。
現在我們已經(jīng)創(chuàng )建并保存了一個(gè)配置文件,讓我們再將它讀取出來(lái)并探究其中包含的數據。
>>> 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'
正如我們在上面所看到的,相關(guān)的 API 相當直觀(guān)。 唯一有些神奇的地方是 DEFAULT
小節,它為所有其他小節提供了默認值 1。 還要注意小節中的鍵大小寫(xiě)不敏感并且會(huì )存儲為小寫(xiě)形式 1。
將多個(gè)配置讀入單個(gè) ConfigParser
是可能的,其中最近添加的配置具有最高優(yōu)先級。 任何沖突的鍵都會(huì )從更近的配置獲取并且先前存在的鍵會(huì )被保留。
>>> another_config = configparser.ConfigParser()
>>> another_config.read('example.ini')
['example.ini']
>>> another_config['topsecret.server.com']['Port']
'50022'
>>> another_config.read_string("[topsecret.server.com]\nPort=48484")
>>> another_config['topsecret.server.com']['Port']
'48484'
>>> another_config.read_dict({"topsecret.server.com": {"Port": 21212}})
>>> another_config['topsecret.server.com']['Port']
'21212'
>>> another_config['topsecret.server.com']['ForwardX11']
'no'
此行為等價(jià)于一次 ConfigParser.read()
調用并向 filenames 形參傳入多個(gè)文件。
支持的數據類(lèi)型?
配置解析器并不會(huì )猜測配置文件中值的類(lèi)型,而總是將它們在內部存儲為字符串。 這意味著(zhù)如果你需要其他數據類(lèi)型,你應當自己來(lái)轉換:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
由于這種任務(wù)十分常用,配置解析器提供了一系列便捷的獲取方法來(lái)處理整數、浮點(diǎn)數和布爾值。 最后一個(gè)類(lèi)型的處理最為有趣,因為簡(jiǎn)單地將值傳給 bool()
是沒(méi)有用的,bool('False')
仍然會(huì )是 True
。 為解決這個(gè)問(wèn)題配置解析器還提供了 getboolean()
。 這個(gè)方法對大小寫(xiě)不敏感并可識別 'yes'
/'no'
, 'on'
/'off'
, 'true'
/'false'
和 '1'
/'0'
1 等布爾值。 例如:
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
除了 getboolean()
,配置解析器還提供了同類(lèi)的 getint()
和 getfloat()
方法。 你可以注冊你自己的轉換器并或是定制已提供的轉換器。 1
回退值?
與字典類(lèi)似,你可以使用某個(gè)小節的 get()
方法來(lái)提供回退值:
>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
請注意默認值會(huì )優(yōu)先于回退值。 例如,在我們的示例中 'CompressionLevel'
鍵僅在 'DEFAULT'
小節被指定。 如果你嘗試在 'topsecret.server.com'
小節獲取它,我們將總是獲取到默認值,即使我們指定了一個(gè)回退值:
>>> topsecret.get('CompressionLevel', '3')
'9'
還需要注意的一點(diǎn)是解析器層級的 get()
方法提供了自定義的更復雜接口,它被維護用于向下兼容。 當使用此方法時(shí),回退值可以通過(guò) fallback
僅限關(guān)鍵字參數來(lái)提供:
>>> config.get('bitbucket.org', 'monster',
... fallback='No such things as monsters')
'No such things as monsters'
同樣的 fallback
參數也可在 getint()
, getfloat()
和 getboolean()
方法中使用,例如:
>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
受支持的 INI 文件結構?
A configuration file consists of sections, each led by a [section]
header,
followed by key/value entries separated by a specific string (=
or :
by
default 1). By default, section names are case sensitive but keys are not
1. Leading and trailing whitespace is removed from keys and values.
Values can be omitted if the parser is configured to allow it 1,
in which case the key/value delimiter may also be left
out. Values can also span multiple lines, as long as they are indented deeper
than the first line of the value. Depending on the parser's mode, blank lines
may be treated as parts of multiline values or ignored.
By default, a valid section name can be any string that does not contain '\n' or ']'.
To change this, see ConfigParser.SECTCRE
.
配置文件可以包含注釋?zhuān)獛в兄付ㄗ址熬Y (默認為 #
和 ;
1)。 注釋可以單獨出現于原本的空白行,并可使用縮進(jìn)。 1
例如:
[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?
值的插值?
在核心功能之上,ConfigParser
還支持插值。 這意味著(zhù)值可以在被 get()
調用返回之前進(jìn)行預處理。
- class configparser.BasicInterpolation?
默認實(shí)現由
ConfigParser
來(lái)使用。 它允許值包含引用了相同小節中其他值或者特殊的默認小節中的值的格式字符串 1。 額外的默認值可以在初始化時(shí)提供。例如:
[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures [Escape] # use a %% to escape the % sign (% is the only character that needs to be escaped): gain: 80%%
在上面的例子里,
ConfigParser
的 interpolation 設為BasicInterpolation()
,這會(huì )將%(home_dir)s
求解為home_dir
的值 (在這里是/Users
)。%(my_dir)s
的將被實(shí)際求解為/Users/lumberjack
。 所有插值都是按需進(jìn)行的,這樣引用鏈中使用的鍵不必以任何特定順序在配置文件中指明。當
interpolation
設為None
時(shí),解析器會(huì )簡(jiǎn)單地返回%(my_dir)s/Pictures
作為my_pictures
的值,并返回%(home_dir)s/lumberjack
作為my_dir
的值。
- class configparser.ExtendedInterpolation?
一個(gè)用于插值的替代處理程序實(shí)現了更高級的語(yǔ)法,它被用于
zc.buildout
中的實(shí)例。 擴展插值使用${section:option}
來(lái)表示來(lái)自外部小節的值。 插值可以跨越多個(gè)層級。 為了方便使用,section:
部分可被省略,插值會(huì )默認作用于當前小節(可能會(huì )從特殊小節獲取默認值)。例如,上面使用基本插值描述的配置,使用擴展插值將是這個(gè)樣子:
[Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures [Escape] # use a $$ to escape the $ sign ($ is the only character that needs to be escaped): cost: $$80
來(lái)自其他小節的值也可以被獲取:
[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
映射協(xié)議訪(fǎng)問(wèn)?
3.2 新版功能.
映射協(xié)議訪(fǎng)問(wèn)這個(gè)通用名稱(chēng)是指允許以字典的方式來(lái)使用自定義對象的功能。 在 configparser
中,映射接口的實(shí)現使用了 parser['section']['option']
標記法。
parser['section']
專(zhuān)門(mén)為解析器中的小節數據返回一個(gè)代理。 這意味著(zhù)其中的值不會(huì )被拷貝,而是在需要時(shí)從原始解析器中獲取。 更為重要的是,當值在小節代理上被修改時(shí),它們其實(shí)是在原始解析器中發(fā)生了改變。
configparser
對象的行為會(huì )盡可能地接近真正的字典。 映射接口是完整而且遵循 MutableMapping
ABC 規范的。 但是,還是有一些差異應當被納入考慮:
默認情況下,小節中的所有鍵是以大小寫(xiě)不敏感的方式來(lái)訪(fǎng)問(wèn)的 1。 例如
for option in parser["section"]
只會(huì )產(chǎn)生optionxform
形式的選項鍵名稱(chēng)。 也就是說(shuō)默認使用小寫(xiě)字母鍵名。 與此同時(shí),對于一個(gè)包含鍵'a'
的小節,以下兩個(gè)表達式均將返回True
:"a" in parser["section"] "A" in parser["section"]
所有小節也包括
DEFAULTSECT
,這意味著(zhù)對一個(gè)小節執行.clear()
可能無(wú)法使得該小節顯示為空。 這是因為默認值是無(wú)法從小節中被刪除的(因為從技術(shù)上說(shuō)它們并不在那里)。 如果它們在小節中被覆蓋,刪除將導致默認值重新變?yōu)榭梢?jiàn)。 嘗試刪除默認值將會(huì )引發(fā)KeyError
。DEFAULTSECT
無(wú)法從解析器中被移除:嘗試刪除將引發(fā)
ValueError
,parser.clear()
會(huì )保留其原狀,parser.popitem()
絕不會(huì )將其返回。
parser.get(section, option, **kwargs)
- 第二個(gè)參數 并非 回退值。 但是請注意小節層級的get()
方法可同時(shí)兼容映射協(xié)議和經(jīng)典配置解析器 API。parser.items()
兼容映射協(xié)議(返回 section_name, section_proxy 對的列表,包括 DEFAULTSECT)。 但是,此方法也可以帶參數發(fā)起調用:parser.items(section, raw, vars)
。 這種調用形式返回指定section
的 option, value 對的列表,將展開(kāi)所有插值(除非提供了raw=True
選項)。
映射協(xié)議是在現有的傳統 API 之上實(shí)現的,以便重載原始接口的子類(lèi)仍然具有符合預期的有效映射。
定制解析器行為?
INI 格式的變種數量幾乎和使用此格式的應用一樣多。 configparser
花費了很大力氣來(lái)為盡量大范圍的可用 INI 樣式提供支持。 默認的可用功能主要由歷史狀況來(lái)確定,你很可能會(huì )想要定制某些特性。
改變特定配置解析器行為的最常見(jiàn)方式是使用 __init__()
選項:
defaults,默認值:
None
此選項接受一個(gè)鍵值對的字典,它將被首先放入
DEFAULT
小節。 這實(shí)現了一種優(yōu)雅的方式來(lái)支持簡(jiǎn)潔的配置文件,它不必指定與已記錄的默認值相同的值。提示:如果你想要為特定的小節指定默認的值,請在讀取實(shí)際文件之前使用
read_dict()
。dict_type,默認值:
dict
此選項主要影響映射協(xié)議的行為和寫(xiě)入配置文件的外觀(guān)。 使用標準字典時(shí),每個(gè)小節是按照它們被加入解析器的順序保存的。 在小節內的選項也是如此。
還有其他替換的字典類(lèi)型可以使用,例如在寫(xiě)回數據時(shí)對小節和選項進(jìn)行排序。
請注意:存在其他方式只用一次操作來(lái)添加鍵值對的集合。 當你在這些操作中使用一個(gè)常規字典時(shí),鍵將按順序進(jìn)行排列。 例如:
>>> parser = configparser.ConfigParser() >>> parser.read_dict({'section1': {'key1': 'value1', ... 'key2': 'value2', ... 'key3': 'value3'}, ... 'section2': {'keyA': 'valueA', ... 'keyB': 'valueB', ... 'keyC': 'valueC'}, ... 'section3': {'foo': 'x', ... 'bar': 'y', ... 'baz': 'z'} ... }) >>> parser.sections() ['section1', 'section2', 'section3'] >>> [option for option in parser['section3']] ['foo', 'bar', 'baz']
allow_no_value,默認值:
False
已知某些配置文件會(huì )包括不帶值的設置,但其在其他方面均符合
configparser
所支持的語(yǔ)法。 構造器的 allow_no_value 形參可用于指明應當接受這樣的值:>>> import configparser >>> sample_config = """ ... [mysqld] ... user = mysql ... pid-file = /var/run/mysqld/mysqld.pid ... skip-external-locking ... old_passwords = 1 ... skip-bdb ... # we don't need ACID today ... skip-innodb ... """ >>> config = configparser.ConfigParser(allow_no_value=True) >>> config.read_string(sample_config) >>> # Settings with values are treated as before: >>> config["mysqld"]["user"] 'mysql' >>> # Settings without values provide None: >>> config["mysqld"]["skip-bdb"] >>> # Settings which aren't specified still raise an error: >>> config["mysqld"]["does-not-exist"] Traceback (most recent call last): ... KeyError: 'does-not-exist'
delimiters,默認值:
('=', ':')
分隔符是用于在小節內分隔鍵和值的子字符串。 在一行中首次出現的分隔子字符串會(huì )被視為一個(gè)分隔符。 這意味著(zhù)值可以包含分隔符(但鍵不可以)。
另請參見(jiàn)
ConfigParser.write()
的 space_around_delimiters 參數。comment_prefixes,默認值:
('#', ';')
inline_comment_prefixes,默認值:
None
注釋前綴是配置文件中用于標示一條有效注釋的開(kāi)頭的字符串。 comment_prefixes 僅用在被視為空白的行(可以縮進(jìn))之前而 inline_comment_prefixes 可用在每個(gè)有效值之后(例如小節名稱(chēng)、選項以及空白的行)。 默認情況下禁用行內注釋?zhuān)⑶?
'#'
和';'
都被用作完整行注釋的前綴。在 3.2 版更改: 在之前的
configparser
版本中行為匹配comment_prefixes=('#',';')
和inline_comment_prefixes=(';',)
。請注意配置解析器不支持對注釋前綴的轉義,因此使用 inline_comment_prefixes 可能妨礙用戶(hù)將被用作注釋前綴的字符指定為可選值。 當有疑問(wèn)時(shí),請避免設置 inline_comment_prefixes。 在許多情況下,在多行值的一行開(kāi)頭存儲注釋前綴字符的唯一方式是進(jìn)行前綴插值,例如:
>>> from configparser import ConfigParser, ExtendedInterpolation >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) >>> # the default BasicInterpolation could be used as well >>> parser.read_string(""" ... [DEFAULT] ... hash = # ... ... [hashes] ... shebang = ... ${hash}!/usr/bin/env python ... ${hash} -*- coding: utf-8 -*- ... ... extensions = ... enabled_extension ... another_extension ... #disabled_by_comment ... yet_another_extension ... ... interpolation not necessary = if # is not at line start ... even in multiline values = line #1 ... line #2 ... line #3 ... """) >>> print(parser['hashes']['shebang']) #!/usr/bin/env python # -*- coding: utf-8 -*- >>> print(parser['hashes']['extensions']) enabled_extension another_extension yet_another_extension >>> print(parser['hashes']['interpolation not necessary']) if # is not at line start >>> print(parser['hashes']['even in multiline values']) line #1 line #2 line #3
strict,默認值:
True
當設為
True
時(shí),解析器在從單一源讀取 (使用read_file()
,read_string()
或read_dict()
) 期間將不允許任何小節或選項出現重復。 推薦在新的應用中使用嚴格解析器。在 3.2 版更改: 在之前的
configparser
版本中行為匹配strict=False
。empty_lines_in_values,默認值:
True
在配置解析器中,值可以包含多行,只要它們的縮進(jìn)級別低于它們所對應的鍵。 默認情況下解析器還會(huì )將空行視為值的一部分。 于此同時(shí),鍵本身也可以任意縮進(jìn)以提升可讀性。 因此,當配置文件變得非常龐大而復雜時(shí),用戶(hù)很容易失去對文件結構的掌控。 例如:
[Section] key = multiline value with a gotcha this = is still a part of the multiline value of 'key'
在用戶(hù)查看時(shí)這可能會(huì )特別有問(wèn)題,如果她是使用比例字體來(lái)編輯文件的話(huà)。 這就是為什么當你的應用不需要帶有空行的值時(shí),你應該考慮禁用它們。 這將使得空行每次都會(huì )作為鍵之間的分隔。 在上面的示例中,空行產(chǎn)生了兩個(gè)鍵,
key
和this
。default_section,默認值:
configparser.DEFAULTSECT
(即:"DEFAULT"
)允許設置一個(gè)保存默認值的特殊節在其他節或插值等目的中使用的慣例是這個(gè)庫所擁有的一個(gè)強大概念,使得用戶(hù)能夠創(chuàng )建復雜的聲明性配置。 這種特殊節通常稱(chēng)為
"DEFAULT"
但也可以被定制為指向任何其他有效的節名稱(chēng)。 一些典型的值包括:"general"
或"common"
。 所提供的名稱(chēng)在從任意節讀取的時(shí)候被用于識別默認的節,而且也會(huì )在將配置寫(xiě)回文件時(shí)被使用。 它的當前值可以使用parser_instance.default_section
屬性來(lái)獲取,并且可以在運行時(shí)被修改(即將文件從一種格式轉換為另一種格式)。interpolation,默認值:
configparser.BasicInterpolation
插值行為可以用通過(guò)提供 interpolation 參數提供自定義處理程序的方式來(lái)定制。
None
可用來(lái)完全禁用插值,ExtendedInterpolation()
提供了一種更高級的變體形式,它的設計受到了zc.buildout
的啟發(fā)。 有關(guān)該主題的更多信息請參見(jiàn) 專(zhuān)門(mén)的文檔章節。RawConfigParser
具有默認的值None
。converters,默認值: 不設置
配置解析器提供了可選的值獲取方法用來(lái)執行類(lèi)型轉換。 默認實(shí)現包括
getint()
,getfloat()
以及getboolean()
。 如果還需要其他獲取方法,用戶(hù)可以在子類(lèi)中定義它們,或者傳入一個(gè)字典,其中每個(gè)鍵都是一個(gè)轉換器的名稱(chēng)而每個(gè)值都是一個(gè)實(shí)現了特定轉換的可調用對象。 例如,傳入{'decimal': decimal.Decimal}
將對解釋器對象和所有節代理添加getdecimal()
。 換句話(huà)說(shuō),可以同時(shí)編寫(xiě)parser_instance.getdecimal('section', 'key', fallback=0)
和parser_instance['section'].getdecimal('key', 0)
。如果轉換器需要訪(fǎng)問(wèn)解析器的狀態(tài),可以在配置解析器子類(lèi)上作為一個(gè)方法來(lái)實(shí)現。 如果該方法的名稱(chēng)是以
get
打頭的,它將在所有節代理上以兼容字典的形式提供(參見(jiàn)上面的getdecimal()
示例)。
更多高級定制選項可通過(guò)重載這些解析器屬性的默認值來(lái)達成。 默認值是在類(lèi)中定義的,因此它們可以通過(guò)子類(lèi)或屬性賦值來(lái)重載。
- ConfigParser.BOOLEAN_STATES?
默認情況下當使用
getboolean()
時(shí),配置解析器會(huì )將下列值視為True
:'1'
,'yes'
,'true'
,'on'
而將下列值視為False
:'0'
,'no'
,'false'
,'off'
。 你可以通過(guò)指定一個(gè)自定義的字符串鍵及其對應的布爾值字典來(lái)重載此行為。 例如:>>> custom = configparser.ConfigParser() >>> custom['section1'] = {'funky': 'nope'} >>> custom['section1'].getboolean('funky') Traceback (most recent call last): ... ValueError: Not a boolean: nope >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} >>> custom['section1'].getboolean('funky') False
其他典型的布爾值對包括
accept
/reject
或enabled
/disabled
。
- ConfigParser.optionxform(option)
這個(gè)方法會(huì )轉換每次 read, get, 或 set 操作的選項名稱(chēng)。 默認會(huì )將名稱(chēng)轉換為小寫(xiě)形式。 這也意味著(zhù)當一個(gè)配置文件被寫(xiě)入時(shí),所有鍵都將為小寫(xiě)形式。 如果此行為不合適則要重載此方法。 例如:
>>> config = """ ... [Section1] ... Key = Value ... ... [Section2] ... AnotherKey = Value ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> list(typical['Section1'].keys()) ['key'] >>> list(typical['Section2'].keys()) ['anotherkey'] >>> custom = configparser.RawConfigParser() >>> custom.optionxform = lambda option: option >>> custom.read_string(config) >>> list(custom['Section1'].keys()) ['Key'] >>> list(custom['Section2'].keys()) ['AnotherKey']
備注
optionxform 函數會(huì )將選項名稱(chēng)轉換為規范形式。 這應該是一個(gè)冪等函數:如果名稱(chēng)已經(jīng)為規范形式,則應不加修改地將其返回。
- ConfigParser.SECTCRE?
一個(gè)已編譯正則表達式會(huì )被用來(lái)解析節標頭。 默認將
[section]
匹配到名稱(chēng)"section"
。 空格會(huì )被視為節名稱(chēng)的一部分,因此[ larch ]
將被讀取為一個(gè)名稱(chēng)為" larch "
的節。 如果此行為不合適則要重載此屬性。 例如:>>> import re >>> config = """ ... [Section 1] ... option = value ... ... [ Section 2 ] ... another = val ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> typical.sections() ['Section 1', ' Section 2 '] >>> custom = configparser.ConfigParser() >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") >>> custom.read_string(config) >>> custom.sections() ['Section 1', 'Section 2']
備注
雖然 ConfigParser 對象也使用
OPTCRE
屬性來(lái)識別選項行,但并不推薦重載它,因為這會(huì )與構造器選項 allow_no_value 和 delimiters 產(chǎn)生沖突。
舊式 API 示例?
主要出于向下兼容性的考慮,configparser
還提供了一種采用顯式 get
/set
方法的舊式 API。 雖然以下介紹的方法存在有效的用例,但對于新項目仍建議采用映射協(xié)議訪(fǎng)問(wèn)。 舊式 API 在多數時(shí)候都更復雜、更底層并且完全違反直覺(jué)。
一個(gè)寫(xiě)入配置文件的示例:
import configparser
config = configparser.RawConfigParser()
# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
config.write(configfile)
一個(gè)再次讀取配置文件的示例:
import configparser
config = configparser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print(config.get('Section1', 'foo'))
要獲取插值,請使用 ConfigParser
:
import configparser
cfg = configparser.ConfigParser()
cfg.read('example.cfg')
# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
'baz': 'evil'}))
# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
# -> "Python is fun!"
print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
# -> "Python is fun!"
print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
# -> "No such things as monsters."
# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:
print(cfg.get('Section1', 'monster', fallback=None))
# -> None
默認值在兩種類(lèi)型的 ConfigParser 中均可用。 它們將在當某個(gè)選項未在別處定義時(shí)被用于插值。
import configparser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print(config.get('Section1', 'foo')) # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo')) # -> "Life is hard!"
ConfigParser 對象?
- class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})?
主配置解析器。 當給定 defaults 時(shí),它會(huì )被初始化為包含固有默認值的字典。 當給定 dict_type 時(shí),它將被用來(lái)創(chuàng )建包含節、節中的選項以及默認值的字典。
當給定 delimiters 時(shí),它會(huì )被用作分隔鍵與值的子字符串的集合。 當給定 comment_prefixes 時(shí),它將被用作在否則為空行的注釋的前綴子字符串的集合。 注釋可以被縮進(jìn)。 當給定 inline_comment_prefixes 時(shí),它將被用作非空行的注釋的前綴子字符串的集合。
當 strict 為
True
(默認值) 時(shí),解析器在從單個(gè)源(文件、字符串或字典)讀取時(shí)將不允許任何節或選項出現重復,否則會(huì )引發(fā)DuplicateSectionError
或DuplicateOptionError
。 當 empty_lines_in_values 為False
(默認值:True
) 時(shí),每個(gè)空行均表示一個(gè)選項的結束。 在其他情況下,一個(gè)多行選項內部的空行會(huì )被保留為值的一部分。 當 allow_no_value 為True
(默認值:False
) 時(shí),將接受沒(méi)有值的選項;此種選項的值將為None
并且它們會(huì )以不帶末尾分隔符的形式被序列化。當給定 default_section 時(shí),它將指定存放其他節的默認值和用于插值的特殊節的名稱(chēng) (通常命名為
"DEFAULT"
)。 該值可通過(guò)使用default_section
實(shí)例屬性在運行時(shí)被讀取或修改。插值行為可通過(guò)給出 interpolation 參數提供自定義處理程序的方式來(lái)定制。
None
可用來(lái)完全禁用插值,ExtendedInterpolation()
提供了一種更高級的變體形式,它的設計受到了zc.buildout
的啟發(fā)。 有關(guān)該主題的更多信息請參見(jiàn) 專(zhuān)門(mén)的文檔章節。插值中使用的所有選項名稱(chēng)將像任何其他選項名稱(chēng)引用一樣通過(guò)
optionxform()
方法來(lái)傳遞。 例如,使用optionxform()
的默認實(shí)現(它會(huì )將選項名稱(chēng)轉換為小寫(xiě)形式)時(shí),值foo %(bar)s
和foo %(BAR)s
是等價(jià)的。當給定 converters 時(shí),它應當為一個(gè)字典,其中每個(gè)鍵代表一個(gè)類(lèi)型轉換器的名稱(chēng)而每個(gè)值則為實(shí)現從字符串到目標數據類(lèi)型的轉換的可調用對象。 每個(gè)轉換器會(huì )獲得其在解析器對象和節代理上對應的
get*()
方法。在 3.1 版更改: 默認的 dict_type 為
collections.OrderedDict
。在 3.2 版更改: 添加了 allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section 以及 interpolation。
在 3.5 版更改: 添加了 converters 參數。
在 3.7 版更改: defaults 參數會(huì )通過(guò)
read_dict()
來(lái)讀取,提供全解析器范圍內一致的行為:非字符串類(lèi)型的鍵和值會(huì )被隱式地轉換為字符串。在 3.8 版更改: 默認的 dict_type 為
dict
,因為它現在會(huì )保留插入順序。- defaults()?
返回包含實(shí)例范圍內默認值的字典。
- sections()?
返回可用節的列表;default section 不包括在該列表中。
- add_section(section)?
向實(shí)例添加一個(gè)名為 section 的節。 如果給定名稱(chēng)的節已存在,將會(huì )引發(fā)
DuplicateSectionError
。 如果傳入了 default section 名稱(chēng),則會(huì )引發(fā)ValueError
。 節名稱(chēng)必須為字符串;如果不是則會(huì )引發(fā)TypeError
。在 3.2 版更改: 非字符串的節名稱(chēng)將引發(fā)
TypeError
。
- has_section(section)?
指明相應名稱(chēng)的 section 是否存在于配置中。 default section 不包含在內。
- options(section)?
返回指定 section 中可用選項的列表。
- has_option(section, option)?
如果給定的 section 存在并且包含給定的 option 則返回
True
;否則返回False
。 如果指定的 section 為None
或空字符串,則會(huì )使用 DEFAULT。
- read(filenames, encoding=None)?
嘗試讀取并解析一個(gè)包含文件名的可迭代對象,返回一個(gè)被成功解析的文件名列表。
如果 filenames 為字符串、
bytes
對象或 path-like object,它會(huì )被當作單個(gè)文件來(lái)處理。 如果 filenames 中名稱(chēng)對應的某個(gè)文件無(wú)法被打開(kāi),該文件將被忽略。 這樣的設計使得你可以指定包含多個(gè)潛在配置文件位置的可迭代對象(例如當前目錄、用戶(hù)家目錄以及某個(gè)系統級目錄),存在于該可迭代對象中的所有配置文件都將被讀取。如果名稱(chēng)對應的文件全都不存在,則
ConfigParser
實(shí)例將包含一個(gè)空數據集。 一個(gè)要求從文件加載初始值的應用應當在調用read()
來(lái)獲取任何可選文件之前使用read_file()
來(lái)加載所要求的一個(gè)或多個(gè)文件:import configparser, os config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
3.2 新版功能: encoding 形參。 在之前的版本中,所有文件都將使用
open()
的默認編碼格式來(lái)讀取。3.6.1 新版功能: filenames 形參接受一個(gè) path-like object。
3.7 新版功能: filenames 形參接受一個(gè)
bytes
對象。
- read_file(f, source=None)?
從 f 讀取并解析配置數據,它必須是一個(gè)產(chǎn)生 Unicode 字符串的可迭代對象(例如以文本模式打開(kāi)的文件)。
可選參數 source 指定要讀取的文件名稱(chēng)。 如果未給出并且 f 具有
name
屬性,則該屬性會(huì )被用作 source;默認值為'<???>'
。3.2 新版功能: 替代
readfp()
。
- read_string(string, source='<string>')?
從字符串中解析配置數據。
可選參數 source 指定一個(gè)所傳入字符串的上下文專(zhuān)屬名稱(chēng)。 如果未給出,則會(huì )使用
'<string>'
。 這通常應為一個(gè)文件系統路徑或 URL。3.2 新版功能.
- read_dict(dictionary, source='<dict>')?
從任意一個(gè)提供了類(lèi)似于字典的
items()
方法的對象加載配置。 鍵為節名稱(chēng),值為包含節中所出現的鍵和值的字典。 如果所用的字典類(lèi)型會(huì )保留順序,則節和其中的鍵將按順序加入。 值會(huì )被自動(dòng)轉換為字符串。可選參數 source 指定一個(gè)所傳入字典的上下文專(zhuān)屬名稱(chēng)。 如果未給出,則會(huì )使用
<dict>
。此方法可被用于在解析器之間拷貝狀態(tài)。
3.2 新版功能.
- get(section, option, *, raw=False, vars=None[, fallback])?
獲取指定名稱(chēng)的 section 的一個(gè) option 的值。 如果提供了 vars,則它必須為一個(gè)字典。 option 的查找順序為 vars*(如果有提供)、*section 以及 DEFAULTSECT。 如果未找到該鍵并且提供了 fallback,則它會(huì )被用作回退值。 可以提供
None
作為 fallback 值。所有
'%'
插值會(huì )在返回值中被展開(kāi),除非 raw 參數為真值。 插值鍵所使用的值會(huì )按與選項相同的方式來(lái)查找。在 3.2 版更改: raw, vars 和 fallback 都是僅限關(guān)鍵字參數,以防止用戶(hù)試圖使用第三個(gè)參數作業(yè)為 fallback 回退值(特別是在使用映射 協(xié)議的時(shí)候)。
- getint(section, option, *, raw=False, vars=None[, fallback])?
將在指定 section 中的 option 強制轉換為整數的便捷方法。 參見(jiàn)
get()
獲取對于 raw, vars 和 fallback 的解釋。
- getfloat(section, option, *, raw=False, vars=None[, fallback])?
將在指定 section 中的 option 強制轉換為浮點(diǎn)數的便捷方法。 參見(jiàn)
get()
獲取對于 raw, vars 和 fallback 的解釋。
- getboolean(section, option, *, raw=False, vars=None[, fallback])?
將在指定 section 中的 option 強制轉換為布爾值的便捷方法。 請注意選項所接受的值為
'1'
,'yes'
,'true'
和'on'
,它們會(huì )使得此方法返回True
,以及'0'
,'no'
,'false'
和'off'
,它們會(huì )使得此方法返回False
。 這些字符串值會(huì )以對大小寫(xiě)不敏感的方式被檢測。 任何其他值都將導致引發(fā)ValueError
。 參見(jiàn)get()
獲取對于 raw, vars 和 fallback 的解釋。
- items(raw=False, vars=None)?
- items(section, raw=False, vars=None)
當未給出 section 時(shí),將返回由 section_name, section_proxy 對組成的列表,包括 DEFAULTSECT。
在其他情況下,將返回給定的 section 中的 option 的 name, value 對組成的列表。 可選參數具有與
get()
方法的參數相同的含義。在 3.8 版更改: vars 中的條目將不在結果中出現。 之前的行為混淆了實(shí)際的解析器選項和為插值提供的變量。
- set(section, option, value)?
如果給定的節存在,則將所給出的選項設為指定的值;在其他情況下將引發(fā)
NoSectionError
。 option 和 value 必須為字符串;如果不是則將引發(fā)TypeError
。
- write(fileobject, space_around_delimiters=True)?
將配置的表示形式寫(xiě)入指定的 file object,該對象必須以文本模式打開(kāi)(接受字符串)。 此表示形式可由將來(lái)的
read()
調用進(jìn)行解析。 如果 space_around_delimiters 為真值,鍵和值之前的分隔符兩邊將加上空格。
備注
原始配置文件中的注釋在寫(xiě)回配置時(shí)不會(huì )被保留。 具體哪些會(huì )被當作注釋?zhuān)Q于為 comment_prefix 和 inline_comment_prefix 所指定的值。
- remove_option(section, option)?
將指定的 option 從指定的 section 中移除。 如果指定的節不存在則會(huì )引發(fā)
NoSectionError
。 如果要移除的選項存在則返回True
;在其他情況下將返回False
。
- remove_section(section)?
從配置中移除指定的 section。 如果指定的節確實(shí)存在則返回
True
。 在其他情況下將返回False
。
- optionxform(option)?
將選項名 option 轉換為輸入文件中的形式或客戶(hù)端代碼所傳入的應當在內部結構中使用的形式。 默認實(shí)現將返回 option 的小寫(xiě)形式版本;子類(lèi)可以重載此行為,或者客戶(hù)端代碼也可以在實(shí)例上設置一個(gè)具有此名稱(chēng)的屬性來(lái)影響此行為。
你不需要子類(lèi)化解析器來(lái)使用此方法,你也可以在一個(gè)實(shí)例上設置它,或使用一個(gè)接受字符串參數并返回字符串的函數。 例如將它設為
str
將使得選項名稱(chēng)變得大小寫(xiě)敏感:cfgparser = ConfigParser() cfgparser.optionxform = str
請注意當讀取配置文件時(shí),選項名稱(chēng)兩邊的空格將在調用
optionxform()
之前被去除。
- readfp(fp, filename=None)?
3.2 版后已移除: 使用
read_file()
來(lái)代替。在 3.2 版更改:
readfp()
現在將在 fp 上執行迭代而不是調用fp.readline()
。對于調用
readfp()
時(shí)傳入不支持迭代的參數的現有代碼,可以在文件類(lèi)對象外使用以下生成器作為包裝器:def readline_generator(fp): line = fp.readline() while line: yield line line = fp.readline()
不再使用
parser.readfp(fp)
而是改用parser.read_file(readline_generator(fp))
。
- configparser.MAX_INTERPOLATION_DEPTH?
當 raw 形參為假值時(shí)
get()
所采用的遞歸插值的最大深度。 這只在使用默認的 interpolation 時(shí)會(huì )起作用。
RawConfigParser 對象?
- class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])?
舊式
ConfigParser
。 它默認禁用插值并且允許通過(guò)不安全的add_section
和set
方法以及舊式defaults=
關(guān)鍵字參數處理來(lái)設置非字符串的節名、選項名和值。在 3.8 版更改: 默認的 dict_type 為
dict
,因為它現在會(huì )保留插入順序。備注
考慮改用
ConfigParser
,它會(huì )檢查內部保存的值的類(lèi)型。 如果你不想要插值,你可以使用ConfigParser(interpolation=None)
。- add_section(section)?
向實(shí)例添加一個(gè)名為 section 的節。 如果給定名稱(chēng)的節已存在,將會(huì )引發(fā)
DuplicateSectionError
。 如果傳入了 default section 名稱(chēng),則會(huì )引發(fā)ValueError
。不檢查 section 以允許用戶(hù)創(chuàng )建以非字符串命名的節。 此行為已不受支持并可能導致內部錯誤。
- set(section, option, value)?
如果給定的節存在,則將給定的選項設為指定的值;在其他情況下將引發(fā)
NoSectionError
。 雖然可能使用RawConfigParser
(或使用ConfigParser
并將 raw 形參設為真值) 以便實(shí)現非字符串值的 internal 存儲,但是完整功能(包括插值和輸出到文件)只能使用字符串值來(lái)實(shí)現。此方法允許用戶(hù)在內部將非字符串值賦給鍵。 此行為已不受支持并會(huì )在嘗試寫(xiě)入到文件或在非原始模式下獲取數據時(shí)導致錯誤。 請使用映射協(xié)議 API,它不允許出現這樣的賦值。
異常?
- exception configparser.Error?
所有其他
configparser
異常的基類(lèi)。
- exception configparser.NoSectionError?
當找不到指定節時(shí)引發(fā)的異常。
- exception configparser.DuplicateSectionError?
當調用
add_section()
時(shí)傳入已存在的節名稱(chēng),或者在嚴格解析器中當單個(gè)輸入文件、字符串或字典內出現重復的節時(shí)引發(fā)的異常。3.2 新版功能: 將可選的
source
和lineno
屬性和參數添加到__init__()
。
- exception configparser.DuplicateOptionError?
當單個(gè)選項在從單個(gè)文件、字符串或字典讀取時(shí)出現兩次時(shí)引發(fā)的異常。 這會(huì )捕獲拼寫(xiě)錯誤和大小寫(xiě)敏感相關(guān)的錯誤,例如一個(gè)字典可能包含兩個(gè)鍵分別代表同一個(gè)大小寫(xiě)不敏感的配置鍵。
- exception configparser.NoOptionError?
當指定的選項未在指定的節中被找到時(shí)引發(fā)的異常。
- exception configparser.InterpolationError?
當執行字符串插值發(fā)生問(wèn)題時(shí)所引發(fā)的異常的基類(lèi)。
- exception configparser.InterpolationDepthError?
當字符串插值由于迭代次數超出
MAX_INTERPOLATION_DEPTH
而無(wú)法完成所引發(fā)的異常。 為InterpolationError
的子類(lèi)。
- exception configparser.InterpolationMissingOptionError?
當從某個(gè)值引用的選項并不存在時(shí)引發(fā)的異常。 為
InterpolationError
的子類(lèi)。
- exception configparser.InterpolationSyntaxError?
當將要執行替換的源文本不符合要求的語(yǔ)法時(shí)引發(fā)的異常。 為
InterpolationError
的子類(lèi)。
- exception configparser.MissingSectionHeaderError?
當嘗試解析一個(gè)不帶節標頭的文件時(shí)引發(fā)的異常。
- exception configparser.ParsingError?
當嘗試解析一個(gè)文件而發(fā)生錯誤時(shí)引發(fā)的異常。
在 3.2 版更改:
filename
屬性和__init__()
參數被重命名為source
以保持一致性。
備注