configparser --- 配置文件解析器?

源代碼: Lib/configparser.py


此模塊提供了它實(shí)現(xiàn)一種基本配置語言 ConfigParser 類,這種語言所提供的結(jié)構(gòu)與 Microsoft Windows INI 文件的類似。 你可以使用這種語言來編寫能夠由最終用戶來自定義的 Python 程序。

注解

這個(gè)庫 并不 能夠解析或?qū)懭朐?Windows Registry 擴(kuò)展版本 INI 語法中所使用的值-類型前綴。

參見

模塊 shlex

支持創(chuàng)建可被用作應(yīng)用配置文件的替代的 Unix 終端式微語言。

模塊 json

json 模塊實(shí)現(xiàn)了一個(gè) JavaScript 語法的子集,它也可被用于這種目的。

快速起步?

讓我們準(zhǔn)備一個(gè)非?;镜呐渲梦募?,它看起來是這樣的:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

INI 文件的結(jié)構(gòu)描述見 以下章節(jié)。 總的來說,這種文件由多個(gè)節(jié)組成,每個(gè)節(jié)包含多個(gè)帶有值的鍵。 configparser 類可以讀取和寫入這種文件。 讓我們先通過程序方式來創(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)
...

如你所見,我們可以把配置解析器當(dāng)作一個(gè)字典來處理。 兩者確實(shí)存在差異,將在后文說明,但是其行為非常接近于字典所具有一般行為。

現(xiàn)在我們已經(jīng)創(chuàng)建并保存了一個(gè)配置文件,讓我們再將它讀取出來并探究其中包含的數(shù)據(jù)。

>>> 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 相當(dāng)直觀。 唯一有些神奇的地方是 DEFAULT 小節(jié),它為所有其他小節(jié)提供了默認(rèn)值 1。 還要注意小節(jié)中的鍵大小寫不敏感并且會(huì)存儲(chǔ)為小寫形式 1。

支持的數(shù)據(jù)類型?

配置解析器并不會(huì)猜測配置文件中值的類型,而總是將它們在內(nèi)部存儲(chǔ)為字符串。 這意味著如果你需要其他數(shù)據(jù)類型,你應(yīng)當(dāng)自己來轉(zhuǎn)換:

>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0

由于這種任務(wù)十分常用,配置解析器提供了一系列便捷的獲取方法來處理整數(shù)、浮點(diǎn)數(shù)和布爾值。 最后一個(gè)類型的處理最為有趣,因?yàn)楹唵蔚貙⒅祩鹘o bool() 是沒有用的,bool('False') 仍然會(huì)是 True。 為解決這個(gè)問題配置解析器還提供了 getboolean()。 這個(gè)方法對大小寫不敏感并可識(shí)別 '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(),配置解析器還提供了同類的 getint()getfloat() 方法。 你可以注冊你自己的轉(zhuǎn)換器并或是定制已提供的轉(zhuǎn)換器。 1

回退值?

與字典類似,你可以使用某個(gè)小節(jié)的 get() 方法來提供回退值:

>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'

請注意默認(rèn)值會(huì)優(yōu)先于回退值。 例如,在我們的示例中 'CompressionLevel' 鍵僅在 'DEFAULT' 小節(jié)被指定。 如果你嘗試在 'topsecret.server.com' 小節(jié)獲取它,我們將總是獲取到默認(rèn)值,即使我們指定了一個(gè)回退值:

>>> topsecret.get('CompressionLevel', '3')
'9'

還需要注意的一點(diǎn)是解析器層級(jí)的 get() 方法提供了自定義的更復(fù)雜接口,它被維護(hù)用于向下兼容。 當(dāng)使用此方法時(shí),回退值可以通過 fallback 僅限關(guān)鍵字參數(shù)來提供:

>>> config.get('bitbucket.org', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'

同樣的 fallback 參數(shù)也可在 getint(), getfloat()getboolean() 方法中使用,例如:

>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False

受支持的 INI 文件結(jié)構(gòu)?

配置文件是由小節(jié)組成的,每個(gè)小節(jié)都有一個(gè) [section] 標(biāo)頭,加上多個(gè)由特定字符串 (默認(rèn)為 =: 1) 分隔的鍵/值條目。 默認(rèn)情況下小節(jié)名對大小寫敏感而鍵對大小寫不敏感 1。 鍵和值開頭和末尾的空格會(huì)被移除。 值可以被省略,在此情況下鍵/值分隔符也可以被省略。 值還可以跨越多行,只要其他行帶有比值的第一行更深的縮進(jìn)。 依據(jù)解析器的具體模式,空白行可能被視為多行值的組成部分也可能被忽略。

配置文件可以包含注釋,要帶有指定字符前綴 (默認(rèn)為 #; 1)。 注釋可以單獨(dú)出現(xiàn)于原本的空白行,并可使用縮進(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 還支持插值。 這意味著值可以在被 get() 調(diào)用返回之前進(jìn)行預(yù)處理。

class configparser.BasicInterpolation?

默認(rèn)實(shí)現(xiàn)由 ConfigParser 來使用。 它允許值包含引用了相同小節(jié)中其他值或者特殊的默認(rèn)小節(jié)中的值的格式字符串 1。 額外的默認(rèn)值可以在初始化時(shí)提供。

例如:

[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

[Escape]
gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)

在上面的例子里,ConfigParserinterpolation 設(shè)為 BasicInterpolation(),這會(huì)將 %(home_dir)s 求解為 home_dir 的值 (在這里是 /Users)。 %(my_dir)s 的將被實(shí)際求解為 /Users/lumberjack。 所有插值都是按需進(jìn)行的,這樣引用鏈中使用的鍵不必以任何特定順序在配置文件中指明。

當(dāng) interpolation 設(shè)為 None 時(shí),解析器會(huì)簡單地返回 %(my_dir)s/Pictures 作為 my_pictures 的值,并返回 %(home_dir)s/lumberjack 作為 my_dir 的值。

class configparser.ExtendedInterpolation?

一個(gè)用于插值的替代處理程序?qū)崿F(xiàn)了更高級(jí)的語法,它被用于 zc.buildout 中的實(shí)例。 擴(kuò)展插值使用 ${section:option} 來表示來自外部小節(jié)的值。 插值可以跨越多個(gè)層級(jí)。 為了方便使用,section: 部分可被省略,插值會(huì)默認(rèn)作用于當(dāng)前小節(jié)(可能會(huì)從特殊小節(jié)獲取默認(rèn)值)。

例如,上面使用基本插值描述的配置,使用擴(kuò)展插值將是這個(gè)樣子:

[Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures

[Escape]
cost: $$80  # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)

來自其他小節(jié)的值也可以被獲取:

[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é)議訪問?

3.2 新版功能.

映射協(xié)議訪問這個(gè)通用名稱是指允許以字典的方式來使用自定義對象的功能。 在 configparser 中,映射接口的實(shí)現(xiàn)使用了 parser['section']['option'] 標(biāo)記法。

parser['section'] 專門為解析器中的小節(jié)數(shù)據(jù)返回一個(gè)代理。 這意味著其中的值不會(huì)被拷貝,而是在需要時(shí)從原始解析器中獲取。 更為重要的是,當(dāng)值在小節(jié)代理上被修改時(shí),它們其實(shí)是在原始解析器中發(fā)生了改變。

configparser 對象的行為會(huì)盡可能地接近真正的字典。 映射接口是完整而且遵循 MutableMapping ABC 規(guī)范的。 但是,還是有一些差異應(yīng)當(dāng)被納入考慮:

  • 默認(rèn)情況下,小節(jié)中的所有鍵是以大小寫不敏感的方式來訪問的 1。 例如 for option in parser["section"] 只會(huì)產(chǎn)生 optionxform 形式的選項(xiàng)鍵名稱。 也就是說默認(rèn)使用小寫字母鍵名。 與此同時(shí),對于一個(gè)包含鍵 'a' 的小節(jié),以下兩個(gè)表達(dá)式均將返回 True:

    "a" in parser["section"]
    "A" in parser["section"]
    
  • 所有小節(jié)也包括 DEFAULTSECT,這意味著對一個(gè)小節(jié)執(zhí)行 .clear() 可能無法使得該小節(jié)顯示為空。 這是因?yàn)槟J(rèn)值是無法從小節(jié)中被刪除的(因?yàn)閺募夹g(shù)上說它們并不在那里)。 如果它們在小節(jié)中被覆蓋,刪除將導(dǎo)致默認(rèn)值重新變?yōu)榭梢姟?嘗試刪除默認(rèn)值將會(huì)引發(fā) KeyError。

  • DEFAULTSECT 無法從解析器中被移除:

    • 嘗試刪除將引發(fā) ValueError

    • parser.clear() 會(huì)保留其原狀,

    • parser.popitem() 絕不會(huì)將其返回。

  • parser.get(section, option, **kwargs) - 第二個(gè)參數(shù) 并非 回退值。 但是請注意小節(jié)層級(jí)的 get() 方法可同時(shí)兼容映射協(xié)議和經(jīng)典配置解析器 API。

  • parser.items() 兼容映射協(xié)議(返回 section_name, section_proxy 對的列表,包括 DEFAULTSECT)。 但是,此方法也可以帶參數(shù)發(fā)起調(diào)用: parser.items(section, raw, vars)。 這種調(diào)用形式返回指定 sectionoption, value 對的列表,將展開所有插值(除非提供了 raw=True 選項(xiàng))。

映射協(xié)議是在現(xiàn)有的傳統(tǒng) API 之上實(shí)現(xiàn)的,以便重載原始接口的子類仍然具有符合預(yù)期的有效映射。

定制解析器行為?

INI 格式的變種數(shù)量幾乎和使用此格式的應(yīng)用一樣多。 configparser 花費(fèi)了很大力氣來為盡量大范圍的可用 INI 樣式提供支持。 默認(rèn)的可用功能主要由歷史狀況來確定,你很可能會(huì)想要定制某些特性。

改變特定配置解析器行為的最常見方式是使用 __init__() 選項(xiàng):

  • defaults,默認(rèn)值: None

    此選項(xiàng)接受一個(gè)鍵值對的字典,它將被首先放入 DEFAULT 小節(jié)。 這實(shí)現(xiàn)了一種優(yōu)雅的方式來支持簡潔的配置文件,它不必指定與已記錄的默認(rèn)值相同的值。

    提示:如果你想要為特定的小節(jié)指定默認(rèn)的值,請?jiān)谧x取實(shí)際文件之前使用 read_dict()。

  • dict_type,默認(rèn)值: collections.OrderedDict

    此選項(xiàng)主要影響映射協(xié)議的行為和寫入配置文件的外觀。 使用默認(rèn)的有序字典時(shí),每個(gè)小節(jié)是按照它們被加入解析器的順序保存的。 在小節(jié)內(nèi)的選項(xiàng)也是如此。

    還有其他替換的字典類型可用,例如在寫回?cái)?shù)據(jù)時(shí)對小節(jié)和選項(xiàng)進(jìn)行排序。 你也可以出于性能原因而使用普通字典。

    請注意:也有辦法通過單次操作來添加一組鍵值對。 當(dāng)你在這些操作中使用一個(gè)常規(guī)字典時(shí),鍵將按順序進(jìn)行排列,因?yàn)?dict 類型從 Python 3.7 起將會(huì)保留插入順序。 例如:

    >>> 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,默認(rèn)值: False

    已知某些配置文件會(huì)包括不帶值的設(shè)置,但其在其他方面均符合 configparser 所支持的語法。 構(gòu)造器的 allow_no_value 形參可用于指明應(yīng)當(dāng)接受這樣的值:

    >>> 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,默認(rèn)值: ('=', ':')

    分隔符是用于在小節(jié)內(nèi)分隔鍵和值的子字符串。 在一行中首次出現(xiàn)的分隔子字符串會(huì)被視為一個(gè)分隔符。 這意味著值可以包含分隔符(但鍵不可以)。

    另請參見 ConfigParser.write()space_around_delimiters 參數(shù)。

  • comment_prefixes,默認(rèn)值: ('#', ';')

  • inline_comment_prefixes,默認(rèn)值: None

    注釋前綴是配置文件中用于標(biāo)示一條有效注釋的開頭的字符串。 comment_prefixes 僅用在被視為空白的行(可以縮進(jìn))之前而 inline_comment_prefixes 可用在每個(gè)有效值之后(例如小節(jié)名稱、選項(xiàng)以及空白的行)。 默認(rèn)情況下禁用行內(nèi)注釋,并且 '#'';' 都被用作完整行注釋的前綴。

    在 3.2 版更改: 在之前的 configparser 版本中行為匹配 comment_prefixes=('#',';')inline_comment_prefixes=(';',)

    請注意配置解析器不支持對注釋前綴的轉(zhuǎn)義,因此使用 inline_comment_prefixes 可能妨礙用戶將被用作注釋前綴的字符指定為可選值。 當(dāng)有疑問時(shí),請避免設(shè)置 inline_comment_prefixes。 在許多情況下,在多行值的一行開頭存儲(chǔ)注釋前綴字符的唯一方式是進(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,默認(rèn)值: True

    當(dāng)設(shè)為 True 時(shí),解析器在從單一源讀取 (使用 read_file(), read_string()read_dict()) 期間將不允許任何小節(jié)或選項(xiàng)出現(xiàn)重復(fù)。 推薦在新的應(yīng)用中使用嚴(yán)格解析器。

    在 3.2 版更改: 在之前的 configparser 版本中行為匹配 strict=False。

  • empty_lines_in_values,默認(rèn)值: True

    在配置解析器中,值可以包含多行,只要它們的縮進(jìn)級(jí)別低于它們所對應(yīng)的鍵。 默認(rèn)情況下解析器還會(huì)將空行視為值的一部分。 于此同時(shí),鍵本身也可以任意縮進(jìn)以提升可讀性。 因此,當(dāng)配置文件變得非常龐大而復(fù)雜時(shí),用戶很容易失去對文件結(jié)構(gòu)的掌控。 例如:

    [Section]
    key = multiline
      value with a gotcha
    
     this = is still a part of the multiline value of 'key'
    

    在用戶查看時(shí)這可能會(huì)特別有問題,如果她是使用比例字體來編輯文件的話。 這就是為什么當(dāng)你的應(yīng)用不需要帶有空行的值時(shí),你應(yīng)該考慮禁用它們。 這將使得空行每次都會(huì)作為鍵之間的分隔。 在上面的示例中,空行產(chǎn)生了兩個(gè)鍵,keythis。

  • default_section,默認(rèn)值: configparser.DEFAULTSECT (即: "DEFAULT")

    允許設(shè)置一個(gè)保存默認(rèn)值的特殊節(jié)在其他節(jié)或插值等目的中使用的慣例是這個(gè)庫所擁有的一個(gè)強(qiáng)大概念,使得用戶能夠創(chuàng)建復(fù)雜的聲明性配置。 這種特殊節(jié)通常稱為 "DEFAULT" 但也可以被定制為指向任何其他有效的節(jié)名稱。 一些典型的值包括: "general""common"。 所提供的名稱在從任意節(jié)讀取的時(shí)候被用于識(shí)別默認(rèn)的節(jié),而且也會(huì)在將配置寫回文件時(shí)被使用。 它的當(dāng)前值可以使用 parser_instance.default_section 屬性來獲取,并且可以在運(yùn)行時(shí)被修改(即將文件從一種格式轉(zhuǎn)換為另一種格式)。

  • interpolation,默認(rèn)值: configparser.BasicInterpolation

    插值行為可以用通過提供 interpolation 參數(shù)提供自定義處理程序的方式來定制。 None 可用來完全禁用插值,ExtendedInterpolation() 提供了一種更高級(jí)的變體形式,它的設(shè)計(jì)受到了 zc.buildout 的啟發(fā)。 有關(guān)該主題的更多信息請參見 專門的文檔章節(jié)。 RawConfigParser 具有默認(rèn)的值 None

  • converters,默認(rèn)值: 不設(shè)置

    配置解析器提供了可選的值獲取方法用來執(zhí)行類型轉(zhuǎn)換。 默認(rèn)實(shí)現(xiàn)包括 getint(), getfloat() 以及 getboolean()。 如果還需要其他獲取方法,用戶可以在子類中定義它們,或者傳入一個(gè)字典,其中每個(gè)鍵都是一個(gè)轉(zhuǎn)換器的名稱而每個(gè)值都是一個(gè)實(shí)現(xiàn)了特定轉(zhuǎn)換的可調(diào)用對象。 例如,傳入 {'decimal': decimal.Decimal} 將對解釋器對象和所有節(jié)代理添加 getdecimal()。 換句話說,可以同時(shí)編寫 parser_instance.getdecimal('section', 'key', fallback=0)parser_instance['section'].getdecimal('key', 0)。

    如果轉(zhuǎn)換器需要訪問解析器的狀態(tài),可以在配置解析器子類上作為一個(gè)方法來實(shí)現(xiàn)。 如果該方法的名稱是以 get 打頭的,它將在所有節(jié)代理上以兼容字典的形式提供(參見上面的 getdecimal() 示例)。

更多高級(jí)定制選項(xiàng)可通過重載這些解析器屬性的默認(rèn)值來達(dá)成。 默認(rèn)值是在類中定義的,因此它們可以通過子類或?qū)傩再x值來重載。

ConfigParser.BOOLEAN_STATES?

默認(rèn)情況下當(dāng)使用 getboolean() 時(shí),配置解析器會(huì)將下列值視為 True: '1', 'yes', 'true', 'on' 而將下列值視為 False: '0', 'no', 'false', 'off'。 你可以通過指定一個(gè)自定義的字符串鍵及其對應(yīng)的布爾值字典來重載此行為。 例如:

>>> 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/rejectenabled/disabled。

ConfigParser.optionxform(option)?

這個(gè)方法會(huì)轉(zhuǎn)換每次 read, get, 或 set 操作的選項(xiàng)名稱。 默認(rèn)會(huì)將名稱轉(zhuǎn)換為小寫形式。 這也意味著當(dāng)一個(gè)配置文件被寫入時(shí),所有鍵都將為小寫形式。 如果此行為不合適則要重載此方法。 例如:

>>> 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 函數(shù)會(huì)將選項(xiàng)名稱轉(zhuǎn)換為規(guī)范形式。 這應(yīng)該是一個(gè)冪等函數(shù):如果名稱已經(jīng)為規(guī)范形式,則應(yīng)不加修改地將其返回。

ConfigParser.SECTCRE?

一個(gè)已編譯正則表達(dá)式會(huì)被用來解析節(jié)標(biāo)頭。 默認(rèn)將 [section] 匹配到名稱 "section"。 空格會(huì)被視為節(jié)名稱的一部分,因此 [  larch  ] 將被讀取為一個(gè)名稱為 "  larch  " 的節(jié)。 如果此行為不合適則要重載此屬性。 例如:

>>> 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 屬性來識(shí)別選項(xiàng)行,但并不推薦重載它,因?yàn)檫@會(huì)與構(gòu)造器選項(xiàng) allow_no_valuedelimiters 產(chǎn)生沖突。

舊式 API 示例?

主要出于向下兼容性的考慮,configparser 還提供了一種采用顯式 get/set 方法的舊式 API。 雖然以下介紹的方法存在有效的用例,但對于新項(xiàng)目仍建議采用映射協(xié)議訪問。 舊式 API 在多數(shù)時(shí)候都更復(fù)雜、更底層并且完全違反直覺。

一個(gè)寫入配置文件的示例:

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

默認(rèn)值在兩種類型的 ConfigParser 中均可用。 它們將在當(dāng)某個(gè)選項(xiàng)未在別處定義時(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=collections.OrderedDict, 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={})?

主配置解析器。 當(dāng)給定 defaults 時(shí),它會(huì)被初始化為包含固有默認(rèn)值的字典。 當(dāng)給定 dict_type 時(shí),它將被用來創(chuàng)建包含節(jié)、節(jié)中的選項(xiàng)以及默認(rèn)值的字典。

當(dāng)給定 delimiters 時(shí),它會(huì)被用作分隔鍵與值的子字符串的集合。 當(dāng)給定 comment_prefixes 時(shí),它將被用作在否則為空行的注釋的前綴子字符串的集合。 注釋可以被縮進(jìn)。 當(dāng)給定 inline_comment_prefixes 時(shí),它將被用作非空行的注釋的前綴子字符串的集合。

當(dāng) strictTrue (默認(rèn)值) 時(shí),解析器在從單個(gè)源(文件、字符串或字典)讀取時(shí)將不允許任何節(jié)或選項(xiàng)出現(xiàn)重復(fù),否則會(huì)引發(fā) DuplicateSectionErrorDuplicateOptionError。 當(dāng) empty_lines_in_valuesFalse (默認(rèn)值: True) 時(shí),每個(gè)空行均表示一個(gè)選項(xiàng)的結(jié)束。 在其他情況下,一個(gè)多行選項(xiàng)內(nèi)部的空行會(huì)被保留為值的一部分。 當(dāng) allow_no_valueTrue (默認(rèn)值: False) 時(shí),將接受沒有值的選項(xiàng);此種選項(xiàng)的值將為 None 并且它們會(huì)以不帶末尾分隔符的形式被序列化。

當(dāng)給定 default_section 時(shí),它將指定存放其他節(jié)的默認(rèn)值和用于插值的特殊節(jié)的名稱 (通常命名為 "DEFAULT")。 該值可通過使用 default_section 實(shí)例屬性在運(yùn)行時(shí)被讀取或修改。

插值行為可通過給出 interpolation 參數(shù)提供自定義處理程序的方式來定制。 None 可用來完全禁用插值,ExtendedInterpolation() 提供了一種更高級(jí)的變體形式,它的設(shè)計(jì)受到了 zc.buildout 的啟發(fā)。 有關(guān)該主題的更多信息請參見 專門的文檔章節(jié)。

插值中使用的所有選項(xiàng)名稱將像任何其他選項(xiàng)名稱引用一樣通過 optionxform() 方法來傳遞。 例如,使用 optionxform() 的默認(rèn)實(shí)現(xiàn)(它會(huì)將選項(xiàng)名稱轉(zhuǎn)換為小寫形式)時(shí),值 foo %(bar)sfoo %(BAR)s 是等價(jià)的。

當(dāng)給定 converters 時(shí),它應(yīng)當(dāng)為一個(gè)字典,其中每個(gè)鍵代表一個(gè)類型轉(zhuǎn)換器的名稱而每個(gè)值則為實(shí)現(xiàn)從字符串到目標(biāo)數(shù)據(jù)類型的轉(zhuǎn)換的可調(diào)用對象。 每個(gè)轉(zhuǎn)換器會(huì)獲得其在解析器對象和節(jié)代理上對應(yīng)的 get*() 方法。

在 3.1 版更改: 默認(rèn)的 dict_typecollections.OrderedDict。

在 3.2 版更改: 添加了 allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section 以及 interpolation。

在 3.5 版更改: 添加了 converters 參數(shù)。

在 3.7 版更改: defaults 參數(shù)會(huì)通過 read_dict() 來讀取,提供全解析器范圍內(nèi)一致的行為:非字符串類型的鍵和值會(huì)被隱式地轉(zhuǎn)換為字符串。

defaults()?

返回包含實(shí)例范圍內(nèi)默認(rèn)值的字典。

sections()?

返回可用節(jié)的列表;default section 不包括在該列表中。

add_section(section)?

向?qū)嵗砑右粋€(gè)名為 section 的節(jié)。 如果給定名稱的節(jié)已存在,將會(huì)引發(fā) DuplicateSectionError。 如果轉(zhuǎn)入了 default section 名稱,則會(huì)引發(fā) ValueError。 節(jié)名稱必須為字符串;如果不是則會(huì)引發(fā) TypeError。

在 3.2 版更改: 非字符串的節(jié)名稱將引發(fā) TypeError。

has_section(section)?

指明相應(yīng)名稱的 section 是否存在于配置中。 default section 不包含在內(nèi)。

options(section)?

返回指定 section 中可用選項(xiàng)的列表。

has_option(section, option)?

如果給定的 section 存在并且包含給定的 option 則返回 True;否則返回 False。 如果指定的 sectionNone 或空字符串,則會(huì)使用 DEFAULT。

read(filenames, encoding=None)?

嘗試讀取并解析一個(gè)包含文件名的可迭代對象,返回一個(gè)被成功解析的文件名列表。

如果 filenames 為字符串、bytes 對象或 path-like object,它會(huì)被當(dāng)作單個(gè)文件來處理。 如果 filenames 中名稱對應(yīng)的某個(gè)文件無法被打開,該文件將被忽略。 這樣的設(shè)計(jì)使得你可以指定包含多個(gè)潛在配置文件位置的可迭代對象(例如當(dāng)前目錄、用戶家目錄以及某個(gè)系統(tǒng)級(jí)目錄),存在于該可迭代對象中的所有配置文件都將被讀取。

如果名稱對應(yīng)的文件全都不存在,則 ConfigParser 實(shí)例將包含一個(gè)空數(shù)據(jù)集。 一個(gè)要求從文件加載初始值的應(yīng)用應(yīng)當(dāng)在調(diào)用 read() 來獲取任何可選文件之前使用 read_file() 來加載所要求的一個(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() 的默認(rèn)編碼格式來讀取。

3.6.1 新版功能: filenames 形參接受一個(gè) path-like object。

3.7 新版功能: filenames 形參接受一個(gè) bytes 對象。

read_file(f, source=None)?

f 讀取并解析配置數(shù)據(jù),它必須是一個(gè)產(chǎn)生 Unicode 字符串的可迭代對象(例如以文本模式打開的文件)。

可選參數(shù) source 指定要讀取的文件名稱。 如果未給出并且 f 具有 name 屬性,則該屬性會(huì)被用作 source;默認(rèn)值為 '<???>'。

3.2 新版功能: 替代 readfp()。

read_string(string, source='<string>')?

從字符串中解析配置數(shù)據(jù)。

可選參數(shù) source 指定一個(gè)所傳入字符串的上下文專屬名稱。 如果未給出,則會(huì)使用 '<string>'。 這通常應(yīng)為一個(gè)文件系統(tǒng)路徑或 URL。

3.2 新版功能.

read_dict(dictionary, source='<dict>')?

從任意一個(gè)提供了類似于字典的 items() 方法的對象加載配置。 鍵為節(jié)名稱,值為包含節(jié)中所出現(xiàn)的鍵和值的字典。 如果所用的字典類型會(huì)保留順序,則節(jié)和其中的鍵將按順序加入。 值會(huì)被自動(dòng)轉(zhuǎn)換為字符串。

可選參數(shù) source 指定一個(gè)所傳入字曲的上下文專屬名稱。 如果未給出,則會(huì)使用 <dict>。

此方法可被用于在解析器之間拷貝狀態(tài)。

3.2 新版功能.

get(section, option, *, raw=False, vars=None[, fallback])?

獲取指定名稱的 section 的一個(gè) option 的值。 如果提供了 vars,則它必須為一個(gè)字典。 option 的查找順序?yàn)?vars*(如果有提供)、*section 以及 DEFAULTSECT。 如果未找到該鍵并且提供了 fallback,則它會(huì)被用作回退值。 可以提供 None 作為 fallback 值。

所有 '%' 插值會(huì)在返回值中被展開,除非 raw 參數(shù)為真值。 插值鍵所使用的值會(huì)按與選項(xiàng)相同的方式來查找。

在 3.2 版更改: raw, varsfallback 都是僅限關(guān)鍵字參數(shù),以防止用戶試圖使用第三個(gè)參數(shù)作業(yè)為 fallback 回退值(特別是在使用映射 協(xié)議的時(shí)候)。

getint(section, option, *, raw=False, vars=None[, fallback])?

將在 section 中指定的 option 強(qiáng)制轉(zhuǎn)換為整數(shù)的便捷方法。 參見 get() 獲取對于 raw, varsfallback 的解釋。

getfloat(section, option, *, raw=False, vars=None[, fallback])?

將在 section 中指定的 option 強(qiáng)制轉(zhuǎn)換為浮點(diǎn)數(shù)的便捷方法。 參見 get() 獲取對于 raw, varsfallback 的解釋。

getboolean(section, option, *, raw=False, vars=None[, fallback])?

將在指定 section 中的 option 強(qiáng)制轉(zhuǎn)換為布爾值的便捷方法。 請注意選項(xiàng)所接受的值為 '1', 'yes', 'true''on',它們會(huì)使得此方法返回 True,以及 '0', 'no', 'false''off',它們會(huì)使得此方法返回 False。 這些字符串值會(huì)以對大小寫不敏感的方式被檢測。 任何其他值都將導(dǎo)致引發(fā) ValueError。 參見 get() 獲取對于 raw, varsfallback 的解釋。

items(raw=False, vars=None)?
items(section, raw=False, vars=None)

當(dāng)未給出 section 時(shí),將返回由 section_name, section_proxy 對組成的列表,包括 DEFAULTSECT。

在其他情況下,將返回給定的 section 中的 option 的 name, value 對組成的列表。 可選參數(shù)具有與 get() 方法的參數(shù)相同的含義。

set(section, option, value)?

如果給定的節(jié)存在,則將所給出的選項(xiàng)設(shè)為指定的值;在其他情況下將引發(fā) NoSectionErroroptionvalue 必須為字符串;如果不是則將引發(fā) TypeError。

write(fileobject, space_around_delimiters=True)?

將配置的表示形式寫入指定的 file object,該對象必須以文本模式打開(接受字符串)。 此表示形式可由將來的 read() 調(diào)用進(jìn)行解析。 如果 space_around_delimiters 為真值,鍵和值之前的分隔符兩邊將加上空格。

remove_option(section, option)?

將指定的 option 從指定的 section 中移除。 如果指定的節(jié)不存在則會(huì)引發(fā) NoSectionError。 如果要移除的選項(xiàng)存在則返回 True;在其他情況下將返回 False。

remove_section(section)?

從配置中移除指定的 section。 如果指定的節(jié)確實(shí)存在則返回 True。 在其他情況下將返回 False

optionxform(option)

將選項(xiàng)名 option 轉(zhuǎn)換為輸入文件中的形式或客戶端代碼所傳入的應(yīng)當(dāng)在內(nèi)部結(jié)構(gòu)中使用的形式。 默認(rèn)實(shí)現(xiàn)將返回 option 的小寫形式版本;子類可以重載此行為,或者客戶端代碼也可以在實(shí)例上設(shè)置一個(gè)具有此名稱的屬性來影響此行為。

你不需要子類化解析器來使用此方法,你也可以在一個(gè)實(shí)例上設(shè)置它,或使用一個(gè)接受字符串參數(shù)并返回字符串的函數(shù)。 例如將它設(shè)為 str 將使得選項(xiàng)名稱變得大小寫敏感:

cfgparser = ConfigParser()
cfgparser.optionxform = str

請注意當(dāng)讀取配置文件時(shí),選項(xiàng)名稱兩邊的空格將在調(diào)用 optionxform() 之前被去除。

readfp(fp, filename=None)?

3.2 版后已移除: 使用 read_file() 來代替。

在 3.2 版更改: readfp() 現(xiàn)在將在 fp 上執(zhí)行迭代而不是調(diào)用 fp.readline()

對于調(diào)用 readfp() 時(shí)傳入不支持迭代的參數(shù)的現(xiàn)有代碼,可以在文件類對象外使用以下生成器作為包裝器:

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?

當(dāng) raw 形參為假值時(shí) get() 所采用的遞歸插值的最大深度。 這只在使用默認(rèn)的 interpolation 時(shí)會(huì)起作用。

RawConfigParser 對象?

class configparser.RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])?

舊式 ConfigParser。 它默認(rèn)禁用插值并且允許通過不安全的 add_sectionset 方法以及舊式 defaults= 關(guān)鍵字參數(shù)處理來設(shè)置非字符串的節(jié)名、選項(xiàng)名和值。

注解

考慮改用 ConfigParser,它會(huì)檢查內(nèi)部保存的值的類型。 如果你不想要插值,你可以使用 ConfigParser(interpolation=None)。

add_section(section)?

向?qū)嵗砑右粋€(gè)名為 section 的節(jié)。 如果給定名稱的節(jié)已存在,將會(huì)引發(fā) DuplicateSectionError。 如果傳入了 default section 名稱,則會(huì)引發(fā) ValueError。

不檢查 section 以允許用戶創(chuàng)建以非字符串命名的節(jié)。 此行為已不受支持并可能導(dǎo)致內(nèi)部錯(cuò)誤。

set(section, option, value)?

如果給定的節(jié)存在,則將給定的選項(xiàng)設(shè)為指定的值;在其他情況下將引發(fā) NoSectionError。 雖然可能使用 RawConfigParser (或使用 ConfigParser 并將 raw 形參設(shè)為真值) 以便實(shí)現(xiàn)非字符串值的 internal 存儲(chǔ),但是完整功能(包括插值和輸出到文件)只能使用字符串值來實(shí)現(xiàn)。

此方法允許用戶在內(nèi)部將非字符串值賦給鍵。 此行為已不受支持并會(huì)在嘗試寫入到文件或在非原始模式下獲取數(shù)據(jù)時(shí)導(dǎo)致錯(cuò)誤。 請使用映射協(xié)議 API,它不允許出現(xiàn)這樣的賦值。

異常?

exception configparser.Error?

所有其他 configparser 異常的基類。

exception configparser.NoSectionError?

當(dāng)找不到指定節(jié)時(shí)引發(fā)的異常。

exception configparser.DuplicateSectionError?

當(dāng)調(diào)用 add_section() 時(shí)傳入已存在的節(jié)名稱,或者在嚴(yán)格解析器中當(dāng)單個(gè)輸入文件、字符串或字典內(nèi)出現(xiàn)重復(fù)的節(jié)時(shí)引發(fā)的異常。

3.2 新版功能: 將可選的 sourcelineno 屬性和參數(shù)添加到 __init__()。

exception configparser.DuplicateOptionError?

當(dāng)單個(gè)選項(xiàng)在從單個(gè)文件、字符串或字典讀取時(shí)出現(xiàn)兩次時(shí)引發(fā)的異常。 這會(huì)捕獲拼寫錯(cuò)誤和大小寫敏感相關(guān)的錯(cuò)誤,例如一個(gè)字典可能包含兩個(gè)鍵分別代表同一個(gè)大小寫不敏感的配置鍵。

exception configparser.NoOptionError?

當(dāng)指定的選項(xiàng)未在指定的節(jié)中被找到時(shí)引發(fā)的異常。

exception configparser.InterpolationError?

當(dāng)執(zhí)行字符串插值發(fā)生問題時(shí)所引發(fā)的異常的基類。

exception configparser.InterpolationDepthError?

當(dāng)字符串插值由于迭代次數(shù)超出 MAX_INTERPOLATION_DEPTH 而無法完成所引發(fā)的異常。 為 InterpolationError 的子類。

exception configparser.InterpolationMissingOptionError?

當(dāng)從某個(gè)值引用的選項(xiàng)并不存在時(shí)引發(fā)的異常。 為 InterpolationError 的子類。

exception configparser.InterpolationSyntaxError?

當(dāng)將要執(zhí)行替換的源文本不符合要求的語法時(shí)引發(fā)的異常。 為 InterpolationError 的子類。

exception configparser.MissingSectionHeaderError?

當(dāng)嘗試解析一個(gè)不帶節(jié)標(biāo)頭的文件時(shí)引發(fā)的異常。

exception configparser.ParsingError?

當(dāng)嘗試解析一個(gè)文件而發(fā)生錯(cuò)誤時(shí)引發(fā)的異常。

在 3.2 版更改: filename 屬性和 __init__() 參數(shù)被重命名為 source 以保持一致性。

備注

1(1,2,3,4,5,6,7,8,9,10)

配置解析器允許重度定制。 如果你有興趣改變腳注說明中所介紹的行為,請參閱 Customizing Parser Behaviour 一節(jié)。