configparser-配置文件分析器

該模塊提供ConfigParser實現基本配置語言的類,該基本配置語言提供的結構類似於Microsoft Windows INI文件中的結構。您可以使用它來編寫可由最終用戶輕鬆定製的Python程序。

快速入門

我們來看一個非常基本的配置文件,如下所示:

[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

由於此任務非常常見,因此配置解析器提供了一系列方便的getter方法來處理整數,浮點數和布爾值。最後一個是最有趣的,因爲僅將值傳遞給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(),config解析器還提供了等價getint()和 getfloat()方法。您可以註冊自己的轉換器並自定義提供的轉換器。1個

後備值

與字典一樣,您可以使用部分的get()方法來提供後備值:

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

請注意,默認值優先於後備值。例如,在我們的示例中,'CompressionLevel'僅在'DEFAULT'部分中指定了密鑰。如果我們嘗試從section中獲取它'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()調用返回值之前對其進行預處理。

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)

在上面的示例中,ConfigParser插值設置爲 BasicInterpolation()會解析%(home_dir)shome_dir/Users在這種情況下)的值 。 %(my_dir)s實際上將解決/Users/lumberjack。所有插值均按需完成,因此不必在配置文件中以任何特定順序指定引用鏈中使用的鍵。

隨着interpolation設置None,解析器僅返回 %(my_dir)s/Pictures作爲的價值my_pictures和 %(home_dir)s/lumberjack作爲價值my_dir

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對象的行爲儘可能接近實際的字典。映射界面已完成,並遵循 MutableMappingABC。但是,應考慮一些差異:

  • 默認情況下,可以不區分大小寫的方式訪問節中的所有鍵 1。例如,僅產生'ed選項鍵名稱。這意味着默認情況下小寫的鍵。同時,對於包含鍵的部分,兩個表達式均返回: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()方法與映射協議和經典的configparser API都兼容。

  • parser.items()與映射協議兼容(返回section_namesection_proxy對的列表, 包括DEFAULTSECT)。但是,也可以使用以下參數調用此方法:。後者調用返回的列表選項在指定的對,與膨脹的所有內插(除非 被提供)。parser.items(section, raw, vars)sectionraw=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'
    
  • 分隔符,默認值:('=', ':')

    分隔符是從部分中的值分隔鍵的子字符串。在一行上第一次出現定界子字符串被視爲定界符。這意味着值(但不能包含鍵)可以包含定界符。

    另請參閱的space_around_delimiters參數 ConfigParser.write()

  • 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
    
  • 嚴格,默認值:True

    當設置爲True,解析器將不允許任何部分或選項重複而從單個源讀取(使用read_file(), read_string()read_dict())。建議在新應用程序中使用嚴格的解析器。

    在3.2版中更改:在以前的版本中,configparser行爲match 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屬性檢索其當前值, 並且可以在運行時進行修改(即,將文件從一種格式轉換爲另一種格式)。

  • 插值,默認值:configparser.BasicInterpolation

    可以通過通過插值參數提供自定義處理程序來自定義插值行爲。None可用於完全關閉插值,ExtendedInterpolation()提供了受啓發的更高級的變體zc.buildout。有關專用主題的更多信息,請參見 專用文檔部分。 RawConfigParser的默認值爲None

  • 轉換器,默認值:未設置

    配置解析器提供執行類型轉換的選項值獲取器。默認情況下getint()getfloat()和 getboolean()被實施。如果需要其他獲取器,則用戶可以在子類中定義它們,或者通過字典,其中每個鍵是轉換器的名稱,每個值是實現所述轉換的可調用項。例如,傳遞將同時添加 解析器對象和所有節代理。換句話說,可以同時編寫 和 。{'decimal': decimal.Decimal}getdecimal()parser_instance.getdecimal('section', 'key', fallback=0)parser_instance['section'].getdecimal('key', 0)

    如果轉換器需要訪問解析器的狀態,則可以將其實現爲配置解析器子類上的方法。如果此方法的名稱以開頭get,則該格式將在所有部分代理中以dict兼容形式出現(請參見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

其他典型的布爾對包括acceptreject或 enableddisabled

ConfigParser.optionxform選項

此方法在每次讀取,獲取或設置操作時都會轉換選項名稱。默認將名稱轉換爲小寫。這也意味着,當寫入配置文件時,所有鍵都將小寫。如果不合適,請重寫此方法。例如:

>>> 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"。空格被認爲是部分名稱的一部分,因此將被視爲name的一部分。如果不合適,請覆蓋此屬性。例如:[  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 還提供了帶有顯式getset方法的舊式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

兩種類型的ConfigParsers中都提供默認值。如果未在其他位置定義使用的選項,則會在插值中使用它們。

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

configparser.ConfigParserdefaults = Nonedict_type = dictallow_no_value = False分隔符=('='':')comment_prefixes =('#'';')inline_comment_prefixes = Nonestrict = Trueempty_lines_in_values = Truedefault_section = configparser.DEFAULTSECT插值= BasicInterpolation()轉換器= {} 

主要配置解析器。當默認給出,它被初始化到內在默認的字典。當dict_type給出,它將被用來創建字典對象的部分名單,對於部分中的選項,併爲默認值。

分隔符給出,它被用作一組,從值分割密鑰的子串。當comment_prefixes給出,它將被用作集前綴,否則空行註釋子的。註釋可以縮進。當指定inline_comment_prefixes時,它將用作在非空行中添加註釋前綴的子字符串集。

strictTrue默認值時(默認),解析器將不允許在從單個源(文件,字符串或字典)讀取,提高DuplicateSectionError或 讀取任何部分或選項重複DuplicateOptionError。當empty_lines_in_valuesFalse (默認值:)時True,每個空行都標記一個選項的結尾。否則,多行選項的內部空行將保留爲值的一部分。當allow_no_valueTrue(默認值:)時False,接受不帶值的選項;否則爲0。這些None元素的值是,並且無需尾隨定界符即可對其進行序列化。

default_section給出,它指定爲其他部分和插值目的的特殊部分保持默認值的名稱(通常命名"DEFAULT")。可以使用default_section實例屬性在運行時檢索和更改此值。

可以通過通過插值參數提供自定義處理程序來自定義插值行爲。None可用於完全關閉插值,ExtendedInterpolation()提供了受啓發的更高級的變體zc.buildout。有關專用主題的更多信息,請參見 專用文檔部分

插值中使用的所有選項名稱都將通過該optionxform()方法傳遞, 就像其他任何選項名稱引用一樣。例如,使用默認實現optionxform()(將選項名稱轉換爲小寫),則值和等效。foo %(bar)sfoo %(BAR)s

轉換器給出,它應該是一個字典,其中每個鍵表示一個類型的轉換器的名稱和每一個值是一個可調用的執行從字符串中的轉化爲期望的數據類型。每個轉換器get*()在解析器對象和部分代理上都有自己的對應方法。

在版本3.1中更改:默認dict_typecollections.OrderedDict

在版本3.2中更改:添加了allow_no_value定界符comment_prefixesstrict, empty_lines_in_valuesdefault_section插值

在3.5版本中改爲:轉換器加入爭論。

改變在3.7版本:默認參數讀取read_dict(),整個分析器提供一致的行爲:非字符串鍵和值隱式轉換爲字符串。

在3.8版中更改:默認dict_typedict,因爲它現在保留插入順序。

defaults()

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

sections()

返回可用部分的列表;在默認的部分不包括在列表中。

add_section

將名爲section的節添加到實例。如果給定名稱的部分已經存在,DuplicateSectionError則引發。如果傳遞了 默認的節名稱,ValueError則會引發。該部分的名稱必須是字符串;如果沒有,TypeError就提出來。

在版本3.2中進行了更改:非字符串節名稱提高了TypeError

has_section

指示配置中是否存在命名部分。該默認部分沒有被確認。

options

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

has_optionsectionoption 

如果給定的部分存在並且包含給定的option,則返回 True; 否則返回False。如果指定的 部分None或爲空字符串,則假定爲DEFAULT。

readfilenamesencoding = None 

嘗試讀取和解析可迭代的文件名,並返回已成功解析的文件名列表。

如果文件名是字符串,bytes對象或類似 路徑的對象,則將其視爲單個文件名。如果無法打開以文件名命名的文件,則該文件將被忽略。這樣設計的目的是,您可以指定可能的配置文件位置的迭代(例如,當前目錄,用戶的主目錄和某些系統範圍的目錄),並將讀取迭代中的所有現有配置文件。

如果不存在任何命名文件,則ConfigParser 實例將包含一個空數據集。需要從文件中加載初始值的應用程序應read_file()在調用read()任何可選文件之前使用加載一個或多個所需文件:

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:編碼參數。以前,所有文件都是使用的默認編碼讀取的open()

在新版本3.6.1:文件名參數接受路徑狀物體

新的版本3.7:文件名參數接受一個bytes對象。

read_filefsource = None 

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

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

版本3.2中的新功能:替換readfp()

read_stringstringsource ='<字符串>' 

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

可選參數source指定所傳遞字符串的特定於上下文的名稱。如果未給出,'<string>'則使用。通常應該是文件系統路徑或URL。

3.2版中的新功能。

read_dict字典source ='<dict>' 

從任何提供類似dict items() 方法的對象中加載配置。鍵是節名,值是帶有鍵和值的字典,應在節中顯示。如果使用的字典類型保留順序,則部分及其鍵將按順序添加。值會自動轉換爲字符串。

可選參數source指定所傳遞字典的特定於上下文的名稱。如果未給出,<dict>則使用。

此方法可用於在解析器之間複製狀態。

3.2版中的新功能。

getsectionoption*raw = Falsevars = None [,fallback ] )

獲取命名部分選項值。如果提供了vars,則它必須是字典。該選項vars(如果提供), sectionDEFAULTSECT中按該順序查找。如果未找到密鑰並提供回退,則將其用作回退值。 可以作爲後備值提供。None

'%'除非raw參數爲true ,否則所有插值都會在返回值中擴展。以與該選項相同的方式查找插值鍵的值。

在版本3.2中更改:參數rawvarsfallback僅作爲關鍵字,以防止用戶嘗試將第三個參數用作後備回退(尤其是在使用映射協議時)。

getintsectionoption*raw = Falsevars = None [,fallback ] )

一種便利方法,用於將指定節中選項強制爲 整數。有關原始var和 後備廣告的說明,請參見。get()

getfloatsectionoption*raw = Falsevars = None [,fallback ] )

一種方便的方法,用於將指定節中選項強制 爲浮點數。有關原始, var後備廣告的說明,請參見。get()

getbooleansectionoption*raw = Falsevars = None [,fallback ] )

一種便利方法,用於將指定部分中選項強制 爲布爾值。請注意,該選項的接受值是 ,,,和,導致該方法返回,和,,,和,這導致它返回。這些字符串值以不區分大小寫的方式檢查。任何其他值都會導致它升高 。有關原始var和 後備廣告的說明,請參見。'1''yes''true''on'True'0''no''false''off'FalseValueErrorget()

itemsraw = Falsevars = None 

itemssectionraw = Falsevars = None 

如果未提供section,則返回section_name和 section_proxy對的列表,包括DEFAULTSECT。

否則,返回給定部分中選項的名稱對列表。可選參數的含義與方法相同 。get()

改變在3.8版本:項目目前在不再出現在結果中。先前的行爲將實際的解析器選項與爲插值提供的變量混合在一起。

setsectionoptionvalue 

如果給定的部分存在,則將給定的選項設置爲指定的值;否則提高NoSectionError。 選項必須是字符串;如果沒有,TypeError就提出來。

writefileobjectspace_around_delimiters = True 

將配置的表示形式寫入指定的文件對象,該對象必須以文本模式(接受字符串)打開。將來的read()調用可以解析此表示。如果 space_around_delimiters爲true,則鍵和值之間的定界符將被空格包圍。

remove_optionsectionoption 

從指定的部分中刪除指定的選項。如果該部分不存在,請引發。如果該選項已存在,則返回;否則返回 。NoSectionErrorTrueFalse

remove_section

從配置中刪除指定的部分。如果該部分實際上存在,請返回True。否則返回False

optionxform選項

將在輸入文件中找到的或由客戶端代碼傳遞的選項名稱選項轉換爲應在內部結構中使用的形式。默認實現返回option的小寫版本 ;子類可以覆蓋此屬性,或者客戶端代碼可以在實例上設置此名稱的屬性以影響此行爲。

您無需繼承解析器的子類即可使用此方法,還可以在實例上將其設置爲具有字符串參數並返回字符串的函數。str例如,將其設置爲,將使選項名稱區分大小寫:

cfgparser = ConfigParser()
cfgparser.optionxform = str

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

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

get()raw 參數爲false 時,遞歸插值的最大深度。僅在使用默認插值時纔有意義 。

RawConfigParser對象

configparser.RawConfigParser默認值= Nonedict_type = dictallow_no_value = False*分隔符=('='':')comment_prefixes =('#'';')inline_comment_prefixes = Nonestrict = Trueempty_lines_in_values = Truedefault_section = configparser.DEFAULTSECT [,插值] )

的舊版變體ConfigParser。它默認情況下禁用插值,並允許通過其unsafe add_sectionset方法以及遺留defaults=關鍵字參數處理來使用非字符串部分名稱,選項名稱和值。

在3.8版中更改:默認dict_typedict,因爲它現在保留插入順序。

注意

 

考慮使用ConfigParser代替哪個檢查要在內部存儲的值的類型。如果不想插值,可以使用ConfigParser(interpolation=None)

add_section

將名爲section的節添加到實例。如果給定名稱的部分已經存在,DuplicateSectionError則引發。如果傳遞了 默認的節名稱,ValueError則會引發。

未選中節的類型,這使用戶可以創建非字符串命名節。不支持此行爲,並且可能會導致內部錯誤。

setsectionoptionvalue 

如果給定的部分存在,則將給定的選項設置爲指定的值;否則提高NoSectionError。儘管可以使用 RawConfigParser(或ConfigParser原始參數設置爲true)內部存儲非字符串值,但僅使用字符串值才能實現全部功能(包括內插和輸出到文件)。

此方法使用戶可以在內部爲鍵分配非字符串值。不支持此行爲,並且在嘗試寫入文件或以非原始模式獲取文件時會導致錯誤。 使用 不允許進行此類分配的映射協議API

異常

異常configparser.Error

所有其他configparser異常的基類。

異常configparser.NoSectionError

未找到指定節時引發異常。

異常configparser.DuplicateSectionError

如果add_section()在單個輸入文件,字符串或字典中多次發現某節,則使用已經存在的節的名稱或在嚴格的解析器中調用if 會引發異常。

版本3.2中的新功能:可選sourcelineno__init__()添加了屬性和參數 。

異常configparser.DuplicateOptionError

如果從單個文件,字符串或字典中讀取單個選項兩次,則嚴格解析器會引發異常。這會捕獲拼寫錯誤和與大小寫敏感有關的錯誤,例如,詞典中可能有兩個鍵代表同一個不區分大小寫的配置鍵。

異常configparser.NoOptionError

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

異常configparser.InterpolationError

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

異常configparser.InterpolationDepthError

由於迭代次數超過不能完成字符串插值時引發的異常MAX_INTERPOLATION_DEPTH。的子類 InterpolationError

異常configparser.InterpolationMissingOptionError

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

異常configparser.InterpolationSyntaxError

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

異常configparser.MissingSectionHeaderError

嘗試分析沒有節頭的文件時引發異常。

異常configparser.ParsingError

嘗試解析文件時發生錯誤時引發異常。

在版本3.2中進行了更改:爲了保持一致,將filename屬性和__init__()參數重命名 source爲。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章