configparser — 配置檔案解析器

原始碼: Lib/configparser.py


此模組提供了 ConfigParser 類,它實現了一種基本的配置語言,該語言提供類似於 Microsoft Windows INI 檔案中找到的結構。您可以使用它來編寫可以由終端使用者輕鬆自定義的 Python 程式。

注意

此庫解釋或寫入 Windows 登錄檔擴充套件版本 INI 語法中使用的值型別字首。

另請參閱

模組 tomllib

TOML 是一個為應用程式配置檔案精心指定的格式。它專門設計為 INI 的改進版本。

模組 shlex

支援建立類似 Unix shell 的迷你語言,這些語言也可用於應用程式配置檔案。

模組 json

json 模組實現了 JavaScript 語法的子集,有時用於配置,但不支援註釋。

快速入門

讓我們來看一個非常基本的配置檔案,如下所示

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

[forge.example]
User = hg

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

INI 檔案的結構在以下部分中描述。本質上,該檔案由多個節組成,每個節都包含帶有值的鍵。configparser 類可以讀取和寫入此類檔案。讓我們從以程式設計方式建立上述配置檔案開始。

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
...                      'Compression': 'yes',
...                      'CompressionLevel': '9'}
>>> config['forge.example'] = {}
>>> config['forge.example']['User'] = 'hg'
>>> config['topsecret.server.example'] = {}
>>> topsecret = config['topsecret.server.example']
>>> 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()
['forge.example', 'topsecret.server.example']
>>> 'forge.example' in config
True
>>> 'python.org' in config
False
>>> config['forge.example']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.example']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['forge.example']:  
...     print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['forge.example']['ForwardX11']
'yes'

如上所述,API 非常簡單。唯一的神奇之處涉及 DEFAULT 節,它為所有其他節提供預設值 [1]。另請注意,節中的鍵不區分大小寫,並以小寫形式儲存 [1]

可以將多個配置讀取到單個 ConfigParser 中,其中最近新增的配置具有最高優先順序。任何衝突的鍵都取自最新的配置,同時保留先前存在的鍵。下面的示例讀取一個 override.ini 檔案,該檔案將覆蓋 example.ini 檔案中的任何衝突鍵。

[DEFAULT]
ServerAliveInterval = -1
>>> config_override = configparser.ConfigParser()
>>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}
>>> with open('override.ini', 'w') as configfile:
...     config_override.write(configfile)
...
>>> config_override = configparser.ConfigParser()
>>> config_override.read(['example.ini', 'override.ini'])
['example.ini', 'override.ini']
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))
-1

此行為等效於呼叫 ConfigParser.read() 並將多個檔案傳遞給 *filenames* 引數。

支援的資料型別

配置解析器不會猜測配置檔案中值的資料型別,始終將其在內部儲存為字串。這意味著如果您需要其他資料型別,則應自行轉換

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

由於此任務非常常見,因此配置解析器提供了一系列方便的 getter 方法來處理整數、浮點數和布林值。最後一個是最有趣的,因為簡單地將值傳遞給 bool() 將毫無用處,因為 bool('False') 仍然是 True。這就是為什麼配置解析器還提供 getboolean() 的原因。此方法不區分大小寫,並從 'yes'/ 'no''on'/ 'off''true'/ 'false''1'/ '0' 識別布林值 [1]。例如

>>> topsecret.getboolean('ForwardX11')
False
>>> config['forge.example'].getboolean('ForwardX11')
True
>>> config.getboolean('forge.example', '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.example' 節獲取它,我們將始終獲得預設值,即使我們指定了回退值

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

另一個需要注意的事情是,解析器級別的 get() 方法提供了一個自定義的、更復雜的介面,該介面是為了向後相容而維護的。使用此方法時,可以透過 fallback 僅關鍵字引數提供回退值

>>> config.get('forge.example', '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],在這種情況下,也可以省略鍵/值分隔符。只要它們比值的首行縮排得更深,值也可以跨越多行。根據解析器的模式,空行可以視為多行值的一部分或被忽略。

預設情況下,有效的節名稱可以是任何不包含“\n”的字串。要更改此設定,請參閱 ConfigParser.SECTCRE

如果解析器配置為允許使用 allow_unnamed_section=True 的未命名頂層節,則可以省略第一個節的名稱。在這種情況下,可以透過 UNNAMED_SECTION 來檢索鍵/值,如 config[UNNAMED_SECTION] 中所示。

配置檔案可以包含註釋,註釋以特定字元為字首(預設情況下為 #; [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?

未命名的節

可以省略第一個節(或唯一節)的名稱,並透過 UNNAMED_SECTION 屬性檢索值。

>>> config = """
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)
>>> unnamed.read_string(config)
>>> unnamed.get(configparser.UNNAMED_SECTION, 'option')
'value'

值的插值

除了核心功能之外,ConfigParser 還支援插值。這意味著可以在從 get() 呼叫返回之前對值進行預處理。

class configparser.BasicInterpolation

ConfigParser 使用的預設實現。它允許值包含格式字串,這些字串引用同一節中的其他值或特殊預設節中的值[1]。可以在初始化時提供其他預設值。

例如

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

在上面的示例中,將插值設定為 BasicInterpolation()ConfigParser 會將 %(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]
# use a $$ to escape the $ sign ($ is the only character that needs to be escaped):
cost: $$80

也可以獲取其他節的值

[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 'ed 選項鍵名稱。這意味著預設情況下是小寫的鍵。同時,對於包含鍵 '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() 方法與對映協議和經典的 configparser API 都相容。

  • parser.items() 與對映協議相容(返回 section_namesection_proxy 對的列表,包括 DEFAULTSECT)。但是,也可以使用引數呼叫此方法:parser.items(section, raw, vars)。後一個呼叫返回指定 sectionoptionvalue 對的列表,其中所有插值都已展開(除非提供了 raw=True)。

對映協議是在現有舊版 API 之上實現的,因此子類覆蓋原始介面仍然應該使對映按預期工作。

自定義解析器行為

INI 格式變體幾乎與使用它的應用程式一樣多。configparser 在為可用的最大合理 INI 樣式集提供支援方面做了很多工作。預設功能主要由歷史背景決定,您很可能需要自定義某些功能。

更改特定配置解析器工作方式的最常見方法是使用 __init__() 選項

  • defaults,預設值:None

    此選項接受鍵值對的字典,該字典將最初放置在 DEFAULT 節中。這為支援簡潔的配置檔案提供了一種優雅的方式,該檔案不指定與文件化預設值相同的值。

    提示:如果要為特定節指定預設值,請在讀取實際檔案之前使用 read_dict()

  • dict_type,預設值:dict

    此選項對對映協議的行為方式以及寫入的配置檔案的外觀有重大影響。對於標準字典,每個節都按照它們新增到解析器的順序儲存。節內的選項也是如此。

    例如,可以使用替代字典型別來對寫回時的節和選項進行排序。

    請注意:有多種方法可以在單個操作中新增一組鍵值對。在這些操作中使用常規字典時,鍵的順序將被排序。例如

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

此方法在每次讀取、獲取或設定操作時轉換選項名稱。預設值將名稱轉換為小寫。這也意味著當寫入配置檔案時,所有鍵都將小寫。如果這不合適,請覆蓋此方法。例如

>>> 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 還提供了一箇舊版 API,其中包含顯式的 get/set 方法。雖然下面概述的方法存在有效的用例,但對於新專案,首選對映協議訪問。舊版 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=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={}, allow_unnamed_section=False)

主要的配置解析器。當提供 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*() 方法。

allow_unnamed_sectionTrue (預設值: False) 時,可以省略第一個節名稱。請參閱 “未命名節”部分

可以將多個配置讀取到單個 ConfigParser 中,其中最近新增的配置具有最高優先順序。任何衝突的鍵都取自最新的配置,同時保留先前存在的鍵。下面的示例讀取一個 override.ini 檔案,該檔案將覆蓋 example.ini 檔案中的任何衝突鍵。

[DEFAULT]
ServerAliveInterval = -1
>>> config_override = configparser.ConfigParser()
>>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}
>>> with open('override.ini', 'w') as configfile:
...     config_override.write(configfile)
...
>>> config_override = configparser.ConfigParser()
>>> config_override.read(['example.ini', 'override.ini'])
['example.ini', 'override.ini']
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))
-1

在 3.1 版本中更改: 預設的 dict_typecollections.OrderedDict

在 3.2 版本中更改: 添加了 allow_no_valuedelimiterscomment_prefixesstrictempty_lines_in_valuesdefault_sectioninterpolation

在 3.5 版本中更改: 添加了 converters 引數。

在 3.7 版本中更改: defaults 引數使用 read_dict() 讀取,在解析器中提供一致的行為:非字串鍵和值隱式轉換為字串。

在 3.8 版本中更改: 預設的 dict_typedict,因為它現在保留了插入順序。

在 3.13 版本中更改: allow_no_valueTrue,並且一個沒有值的鍵繼續使用縮排行時,會引發 MultilineContinuationError

在 3.13 版本中更改: 添加了 allow_unnamed_section 引數。

defaults()

返回一個包含例項範圍預設值的字典。

sections()

返回可用節的列表;*預設節* 不包含在列表中。

add_section(section)

將名為 section 的節新增到例項。如果已存在具有給定名稱的節,則會引發 DuplicateSectionError。如果傳遞了 *預設節* 名稱,則會引發 ValueError。節的名稱必須是字串;如果不是,則會引發 TypeError

在 3.2 版本中更改: 非字串節名稱會引發 TypeError

has_section(section)

指示名為 section 的節是否存在於配置中。*預設節* 不會被識別。

options(section)

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

has_option(section, option)

如果給定的 section 存在,並且包含給定的 option,則返回 True;否則返回 False。如果指定的 sectionNone 或空字串,則假定為 DEFAULT。

read(filenames, encoding=None)

嘗試讀取和解析一個檔名可迭代物件,並返回一個成功解析的檔名列表。

如果 filenames 是一個字串、一個 bytes 物件或一個路徑類物件,則將其視為單個檔名。如果 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* 讀取並解析配置資料,*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*,則它必須是一個字典。 將按照 *vars*(如果提供)、*section* 和 *DEFAULTSECT* 的順序查詢 *option*。 如果找不到鍵且提供了 *fallback*,則將其用作回退值。 可以將 None 提供作為 *fallback* 值。

除非 *raw* 引數為 true,否則將在返回值中展開所有 '%' 插值。 插值鍵的值的查詢方式與選項相同。

在 3.2 版本中變更: 引數 *raw*、*vars* 和 *fallback* 僅是關鍵字引數,以防止使用者嘗試將第三個引數用作 *fallback* 回退(尤其是在使用對映協議時)。

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

一個便捷方法,它將指定 *section* 中的 *option* 強制轉換為整數。 有關 *raw*、*vars* 和 *fallback* 的說明,請參閱 get()

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

一個便捷方法,它將指定 *section* 中的 *option* 強制轉換為浮點數。 有關 *raw*、*vars* 和 *fallback* 的說明,請參閱 get()

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

一個便捷方法,它將指定 *section* 中的 *option* 強制轉換為布林值。 請注意,該選項接受的值為 '1''yes''true''on',這將導致此方法返回 True,而 '0''no''false''off' 會導致它返回 False。 這些字串值會以不區分大小寫的方式進行檢查。 任何其他值都會導致它引發 ValueError。 有關 *raw*、*vars* 和 *fallback* 的說明,請參閱 get()

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

當未給出 *section* 時,返回 section_namesection_proxy 對的列表,包括 DEFAULTSECT。

否則,返回給定 *section* 中選項的 namevalue 對的列表。 可選引數與 get() 方法的含義相同。

在 3.8 版本中變更: *vars* 中存在的項不再顯示在結果中。 先前的行為將實際解析器選項與為插值提供的變數混合在一起。

set(section, option, value)

如果給定的節存在,則將給定的選項設定為指定的值; 否則引發 NoSectionError。 *option* 和 *value* 必須是字串; 如果不是,則引發 TypeError

write(fileobject, space_around_delimiters=True)

將配置的表示形式寫入指定的 檔案物件,該物件必須以文字模式開啟(接受字串)。 此表示形式可由將來的 read() 呼叫解析。 如果 *space_around_delimiters* 為 true,則鍵和值之間的分隔符將用空格包圍。

注意

將配置寫回時,不會保留原始配置檔案中的註釋。 什麼被視為註釋,取決於給定的 *comment_prefix* 和 *inline_comment_prefix* 的值。

remove_option(section, option)

從指定的 *section* 中刪除指定的 *option*。 如果該節不存在,則引發 NoSectionError。 如果存在要刪除的選項,則返回 True;否則返回 False

remove_section(section)

從配置中刪除指定的 *section*。 如果該節確實存在,則返回 True。 否則返回 False

optionxform(option)

轉換在輸入檔案中找到的或由客戶端程式碼傳入的選項名 option,使其成為內部結構中應使用的形式。預設實現返回 option 的小寫版本;子類可以覆蓋此行為,或者客戶端程式碼可以在例項上設定此名稱的屬性來影響此行為。

您無需子類化解析器即可使用此方法,也可以在例項上將其設定為一個函式,該函式接受一個字串引數並返回一個字串。例如,將其設定為 str,將使選項名稱區分大小寫。

cfgparser = ConfigParser()
cfgparser.optionxform = str

請注意,在讀取配置檔案時,會在呼叫 optionxform() 之前,刪除選項名稱周圍的空格。

configparser.UNNAMED_SECTION

一個特殊的物件,表示用於引用未命名部分的部分名稱(請參閱未命名部分)。

configparser.MAX_INTERPOLATION_DEPTH

raw 引數為 false 時,get() 遞迴插值的最大深度。僅當使用預設的 interpolation 時才相關。

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=BasicInterpolation(), converters={}, allow_unnamed_section=False)

ConfigParser 的舊版本。它預設停用插值,並透過其不安全的 add_sectionset 方法以及舊的 defaults= 關鍵字引數處理,允許使用非字串節名稱、選項名稱和值。

在 3.2 版本中更改: 添加了 allow_no_valuedelimiterscomment_prefixesstrictempty_lines_in_valuesdefault_sectioninterpolation

在 3.5 版本中更改: 添加了 converters 引數。

在 3.8 版本中更改: 預設的 dict_typedict,因為它現在保留了插入順序。

在 3.13 版本中更改: 添加了 allow_unnamed_section 引數。

注意

考慮使用 ConfigParser 來代替,它會檢查內部儲存的值的型別。如果您不想要插值,可以使用 ConfigParser(interpolation=None)

add_section(section)

向例項新增名為 section 的節。如果已存在具有給定名稱的節,則會引發 DuplicateSectionError。如果傳遞的是 預設節 名稱,則會引發 ValueError

不檢查 section 的型別,這允許使用者建立非字串命名的節。此行為不受支援,並可能導致內部錯誤。

set(section, option, value)

如果給定節存在,則將給定選項設定為指定值;否則引發 NoSectionError。雖然可以使用 RawConfigParser (或 ConfigParser,並將 raw 引數設定為 true)來 內部 儲存非字串值,但只有使用字串值才能實現全部功能(包括插值和輸出到檔案)。

此方法允許使用者在內部將非字串值分配給鍵。此行為不受支援,並且在嘗試寫入檔案或在非原始模式下獲取時會導致錯誤。請使用對映協議 API,該 API 不允許進行此類分配。

異常

exception configparser.Error

所有其他 configparser 異常的基類。

exception configparser.NoSectionError

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

exception configparser.DuplicateSectionError

如果使用已存在的節的名稱呼叫 add_section(),或者在嚴格解析器中,如果在單個輸入檔案、字串或字典中多次找到節,則會引發此異常。

在 3.2 版本中更改: __init__() 添加了可選的 sourcelineno 屬性和引數。

exception configparser.DuplicateOptionError

如果單個選項在從單個檔案、字串或字典讀取期間出現兩次,則由嚴格解析器引發的異常。這會捕獲拼寫錯誤和與大小寫敏感性相關的錯誤,例如,字典可能具有兩個鍵,表示相同的不區分大小寫的配置鍵。

exception configparser.NoOptionError

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

exception configparser.InterpolationError

執行字串插值時出現問題時引發的異常的基類。

exception configparser.InterpolationDepthError

當字串插值無法完成,因為迭代次數超過 MAX_INTERPOLATION_DEPTH 時引發的異常。InterpolationError 的子類。

exception configparser.InterpolationMissingOptionError

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

異常 configparser.InterpolationSyntaxError

當進行替換的源文字不符合所需的語法時引發的異常。 是 InterpolationError 的子類。

異常 configparser.MissingSectionHeaderError

當嘗試解析沒有節頭的檔案時引發的異常。

異常 configparser.ParsingError

當嘗試解析檔案時發生錯誤時引發的異常。

在 3.12 版本中變更:filename 屬性和 __init__() 建構函式引數已被移除。 自 3.2 版本以來,它們已使用 source 名稱提供。

異常 configparser.MultilineContinuationError

當沒有對應值的鍵以縮排行繼續時引發的異常。

在 3.13 版本中新增。

腳註