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

源代碼: Lib/configparser.py


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

注解

這個庫 并不 能夠解析或寫入在 Windows Registry 擴展版本 INI 語法中所使用的值-類型前綴。

參見

模塊 shlex

支持創建可被用作應用配置文件的替代的 Unix 終端式微語言。

模塊 json

json 模塊實現了一個 JavaScript 語法的子集,它也可被用于這種目的。

快速起步?

讓我們準備一個非常基本的配置文件,它看起來是這樣的:

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

[bitbucket.org]
User = hg

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

INI 文件的結構描述見 以下章節。 總的來說,這種文件由多個節組成,每個節包含多個帶有值的鍵。 configparser 類可以讀取和寫入這種文件。 讓我們先通過程序方式來創建上述的配置文件。

>>> 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)
...

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

現在我們已經創建并保存了一個配置文件,讓我們再將它讀取出來并探究其中包含的數據。

>>> 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'

正如我們在上面所看到的,相關的 API 相當直觀。 唯一有些神奇的地方是 DEFAULT 小節,它為所有其他小節提供了默認值 1。 還要注意小節中的鍵大小寫不敏感并且會存儲為小寫形式 1

支持的數據類型?

配置解析器并不會猜測配置文件中值的類型,而總是將它們在內部存儲為字符串。 這意味著如果你需要其他數據類型,你應當自己來轉換:

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

由于這種任務十分常用,配置解析器提供了一系列便捷的獲取方法來處理整數、浮點數和布爾值。 最后一個類型的處理最為有趣,因為簡單地將值傳給 bool() 是沒有用的,bool('False') 仍然會是 True。 為解決這個問題配置解析器還提供了 getboolean()。 這個方法對大小寫不敏感并可識別 '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() 方法。 你可以注冊你自己的轉換器并或是定制已提供的轉換器。 1

回退值?

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

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

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

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

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

>>> 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 文件結構?

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

配置文件可以包含注釋,要帶有指定字符前綴 (默認為 #; 1)。 注釋可以單獨出現于原本的空白行,并可使用縮進。 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() 調用返回之前進行預處理。

class configparser.BasicInterpolation?

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

例如:

[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 設為 BasicInterpolation(),這會將 %(home_dir)s 求解為 home_dir 的值 (在這里是 /Users)。 %(my_dir)s 的將被實際求解為 /Users/lumberjack。 所有插值都是按需進行的,這樣引用鏈中使用的鍵不必以任何特定順序在配置文件中指明。

interpolation 設為 None 時,解析器會簡單地返回 %(my_dir)s/Pictures 作為 my_pictures 的值,并返回 %(home_dir)s/lumberjack 作為 my_dir 的值。

class configparser.ExtendedInterpolation?

一個用于插值的替代處理程序實現了更高級的語法,它被用于 zc.buildout 中的實例。 擴展插值使用 ${section:option} 來表示來自外部小節的值。 插值可以跨越多個層級。 為了方便使用,section: 部分可被省略,插值會默認作用于當前小節(可能會從特殊小節獲取默認值)。

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

[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)

來自其他小節的值也可以被獲取:

[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}

映射協議訪問?

3.2 新版功能.

映射協議訪問這個通用名稱是指允許以字典的方式來使用自定義對象的功能。 在 configparser 中,映射接口的實現使用了 parser['section']['option'] 標記法。

parser['section'] 專門為解析器中的小節數據返回一個代理。 這意味著其中的值不會被拷貝,而是在需要時從原始解析器中獲取。 更為重要的是,當值在小節代理上被修改時,它們其實是在原始解析器中發生了改變。

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

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

    "a" in parser["section"]
    "A" in parser["section"]
    
  • 所有小節也包括 DEFAULTSECT,這意味著對一個小節執行 .clear() 可能無法使得該小節顯示為空。 這是因為默認值是無法從小節中被刪除的(因為從技術上說它們并不在那里)。 如果它們在小節中被覆蓋,刪除將導致默認值重新變為可見。 嘗試刪除默認值將會引發 KeyError

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

    • 嘗試刪除將引發 ValueError

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

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

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

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

映射協議是在現有的傳統 API 之上實現的,以便重載原始接口的子類仍然具有符合預期的有效映射。

定制解析器行為?

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

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

  • defaults,默認值: None

    此選項接受一個鍵值對的字典,它將被首先放入 DEFAULT 小節。 這實現了一種優雅的方式來支持簡潔的配置文件,它不必指定與已記錄的默認值相同的值。

    提示:如果你想要為特定的小節指定默認的值,請在讀取實際文件之前使用 read_dict()

  • dict_type,默認值: collections.OrderedDict

    此選項主要影響映射協議的行為和寫入配置文件的外觀。 使用默認的有序字典時,每個小節是按照它們被加入解析器的順序保存的。 在小節內的選項也是如此。

    還有其他替換的字典類型可用,例如在寫回數據時對小節和選項進行排序。 你也可以出于性能原因而使用普通字典。

    請注意:也有辦法通過單次操作來添加一組鍵值對。 當你在這些操作中使用一個常規字典時,鍵將按順序進行排列,因為 dict 類型從 Python 3.7 起將會保留插入順序。 例如:

    >>> 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

    已知某些配置文件會包括不帶值的設置,但其在其他方面均符合 configparser 所支持的語法。 構造器的 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,默認值: ('=', ':')

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

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

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

  • inline_comment_prefixes,默認值: None

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

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

    請注意配置解析器不支持對注釋前綴的轉義,因此使用 inline_comment_prefixes 可能妨礙用戶將被用作注釋前綴的字符指定為可選值。 當有疑問時,請避免設置 inline_comment_prefixes。 在許多情況下,在多行值的一行開頭存儲注釋前綴字符的唯一方式是進行前綴插值,例如:

    >>> 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 時,解析器在從單一源讀取 (使用 read_file(), read_string()read_dict()) 期間將不允許任何小節或選項出現重復。 推薦在新的應用中使用嚴格解析器。

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

  • empty_lines_in_values,默認值: True

    在配置解析器中,值可以包含多行,只要它們的縮進級別低于它們所對應的鍵。 默認情況下解析器還會將空行視為值的一部分。 于此同時,鍵本身也可以任意縮進以提升可讀性。 因此,當配置文件變得非常龐大而復雜時,用戶很容易失去對文件結構的掌控。 例如:

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

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

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

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

  • interpolation,默認值: configparser.BasicInterpolation

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

  • converters,默認值: 不設置

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

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

更多高級定制選項可通過重載這些解析器屬性的默認值來達成。 默認值是在類中定義的,因此它們可以通過子類或屬性賦值來重載。

ConfigParser.BOOLEAN_STATES?

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

>>> 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)?

這個方法會轉換每次 read, get, 或 set 操作的選項名稱。 默認會將名稱轉換為小寫形式。 這也意味著當一個配置文件被寫入時,所有鍵都將為小寫形式。 如果此行為不合適則要重載此方法。 例如:

>>> 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 函數會將選項名稱轉換為規范形式。 這應該是一個冪等函數:如果名稱已經為規范形式,則應不加修改地將其返回。

ConfigParser.SECTCRE?

一個已編譯正則表達式會被用來解析節標頭。 默認將 [section] 匹配到名稱 "section"。 空格會被視為節名稱的一部分,因此 [  larch  ] 將被讀取為一個名稱為 "  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 屬性來識別選項行,但并不推薦重載它,因為這會與構造器選項 allow_no_valuedelimiters 產生沖突。

舊式 API 示例?

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

一個寫入配置文件的示例:

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)

一個再次讀取配置文件的示例:

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

默認值在兩種類型的 ConfigParser 中均可用。 它們將在當某個選項未在別處定義時被用于插值。

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={})?

主配置解析器。 當給定 defaults 時,它會被初始化為包含固有默認值的字典。 當給定 dict_type 時,它將被用來創建包含節、節中的選項以及默認值的字典。

當給定 delimiters 時,它會被用作分隔鍵與值的子字符串的集合。 當給定 comment_prefixes 時,它將被用作在否則為空行的注釋的前綴子字符串的集合。 注釋可以被縮進。 當給定 inline_comment_prefixes 時,它將被用作非空行的注釋的前綴子字符串的集合。

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

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

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

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

當給定 converters 時,它應當為一個字典,其中每個鍵代表一個類型轉換器的名稱而每個值則為實現從字符串到目標數據類型的轉換的可調用對象。 每個轉換器會獲得其在解析器對象和節代理上對應的 get*() 方法。

在 3.1 版更改: 默認的 dict_typecollections.OrderedDict

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

在 3.5 版更改: 添加了 converters 參數。

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

defaults()?

返回包含實例范圍內默認值的字典。

sections()?

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

add_section(section)?

向實例添加一個名為 section 的節。 如果給定名稱的節已存在,將會引發 DuplicateSectionError。 如果轉入了 default section 名稱,則會引發 ValueError。 節名稱必須為字符串;如果不是則會引發 TypeError

在 3.2 版更改: 非字符串的節名稱將引發 TypeError

has_section(section)?

指明相應名稱的 section 是否存在于配置中。 default section 不包含在內。

options(section)?

返回指定 section 中可用選項的列表。

has_option(section, option)?

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

read(filenames, encoding=None)?

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

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

如果名稱對應的文件全都不存在,則 ConfigParser 實例將包含一個空數據集。 一個要求從文件加載初始值的應用應當在調用 read() 來獲取任何可選文件之前使用 read_file() 來加載所要求的一個或多個文件:

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() 的默認編碼格式來讀取。

3.6.1 新版功能: filenames 形參接受一個 path-like object

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

read_file(f, source=None)?

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

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

3.2 新版功能: 替代 readfp()

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

從字符串中解析配置數據。

可選參數 source 指定一個所傳入字符串的上下文專屬名稱。 如果未給出,則會使用 '<string>'。 這通常應為一個文件系統路徑或 URL。

3.2 新版功能.

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

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

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

此方法可被用于在解析器之間拷貝狀態。

3.2 新版功能.

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

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

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

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

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

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

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

將在 section 中指定的 option 強制轉換為浮點數的便捷方法。 參見 get() 獲取對于 raw, varsfallback 的解釋。

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

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

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

當未給出 section 時,將返回由 section_name, section_proxy 對組成的列表,包括 DEFAULTSECT。

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

set(section, option, value)?

如果給定的節存在,則將所給出的選項設為指定的值;在其他情況下將引發 NoSectionErroroptionvalue 必須為字符串;如果不是則將引發 TypeError

write(fileobject, space_around_delimiters=True)?

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

remove_option(section, option)?

將指定的 option 從指定的 section 中移除。 如果指定的節不存在則會引發 NoSectionError。 如果要移除的選項存在則返回 True;在其他情況下將返回 False

remove_section(section)?

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

optionxform(option)

將選項名 option 轉換為輸入文件中的形式或客戶端代碼所傳入的應當在內部結構中使用的形式。 默認實現將返回 option 的小寫形式版本;子類可以重載此行為,或者客戶端代碼也可以在實例上設置一個具有此名稱的屬性來影響此行為。

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

cfgparser = ConfigParser()
cfgparser.optionxform = str

請注意當讀取配置文件時,選項名稱兩邊的空格將在調用 optionxform() 之前被去除。

readfp(fp, filename=None)?

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

在 3.2 版更改: readfp() 現在將在 fp 上執行迭代而不是調用 fp.readline()

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

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 形參為假值時 get() 所采用的遞歸插值的最大深度。 這只在使用默認的 interpolation 時會起作用。

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。 它默認禁用插值并且允許通過不安全的 add_sectionset 方法以及舊式 defaults= 關鍵字參數處理來設置非字符串的節名、選項名和值。

注解

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

add_section(section)?

向實例添加一個名為 section 的節。 如果給定名稱的節已存在,將會引發 DuplicateSectionError。 如果傳入了 default section 名稱,則會引發 ValueError

不檢查 section 以允許用戶創建以非字符串命名的節。 此行為已不受支持并可能導致內部錯誤。

set(section, option, value)?

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

此方法允許用戶在內部將非字符串值賦給鍵。 此行為已不受支持并會在嘗試寫入到文件或在非原始模式下獲取數據時導致錯誤。 請使用映射協議 API,它不允許出現這樣的賦值。

異常?

exception configparser.Error?

所有其他 configparser 異常的基類。

exception configparser.NoSectionError?

當找不到指定節時引發的異常。

exception configparser.DuplicateSectionError?

當調用 add_section() 時傳入已存在的節名稱,或者在嚴格解析器中當單個輸入文件、字符串或字典內出現重復的節時引發的異常。

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

exception configparser.DuplicateOptionError?

當單個選項在從單個文件、字符串或字典讀取時出現兩次時引發的異常。 這會捕獲拼寫錯誤和大小寫敏感相關的錯誤,例如一個字典可能包含兩個鍵分別代表同一個大小寫不敏感的配置鍵。

exception configparser.NoOptionError?

當指定的選項未在指定的節中被找到時引發的異常。

exception configparser.InterpolationError?

當執行字符串插值發生問題時所引發的異常的基類。

exception configparser.InterpolationDepthError?

當字符串插值由于迭代次數超出 MAX_INTERPOLATION_DEPTH 而無法完成所引發的異常。 為 InterpolationError 的子類。

exception configparser.InterpolationMissingOptionError?

當從某個值引用的選項并不存在時引發的異常。 為 InterpolationError 的子類。

exception configparser.InterpolationSyntaxError?

當將要執行替換的源文本不符合要求的語法時引發的異常。 為 InterpolationError 的子類。

exception configparser.MissingSectionHeaderError?

當嘗試解析一個不帶節標頭的文件時引發的異常。

exception configparser.ParsingError?

當嘗試解析一個文件而發生錯誤時引發的異常。

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

備注

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

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