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 文件的结构在下一节中描述。本质上,文件由多个节(section)组成,每个节包含带有值的键(key)。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)组成,每个节由 [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%%

在上面的例子中,将 interpolation 设置为 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 处理后的选项键名。默认情况下这意味着键名是小写的。同时,对于一个包含键 '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() 与映射协议兼容(返回一个包含 DEFAULTSECT 的 section_name, section_proxy 对的列表)。但是,此方法也可以带参数调用:parser.items(section, raw, vars)。后一种调用返回指定 sectionoption, value 对的列表,所有插值都已展开(除非提供了 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 也提供了一个带有显式 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

两种类型的 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 对象

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_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_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 参数接受一个类路径对象

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

获取指定 sectionoption 值。如果提供了 vars,它必须是一个字典。option 将按顺序在 vars(如果提供)、sectionDEFAULTSECT 中查找。如果未找到键且提供了 fallback,则使用它作为回退值。可以将 None 作为 fallback 值提供。

除非 raw 参数为 true,否则返回值中的所有 '%' 插值都会被展开。插值键的值会以与选项相同的方式进行查找。

在 3.2 版更改: 参数 rawvarsfallback 仅为关键字参数,以保护用户不尝试将第三个参数用作 fallback 回退(特别是在使用映射协议时)。

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

一个方便的方法,将指定 section 中的 option 强制转换为整数。有关 rawvarsfallback 的解释,请参见 get()

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

一个方便的方法,将指定 section 中的 option 强制转换为浮点数。有关 rawvarsfallback 的解释,请参见 get()

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

一个方便的方法,将指定 section 中的 option 强制转换为布尔值。请注意,该选项可接受的值为 '1''yes''true''on',这些值会使此方法返回 True;以及 '0''no''false''off',这些值会使其返回 False。这些字符串值的检查不区分大小写。任何其他值都会导致它引发 ValueError。有关 rawvarsfallback 的解释,请参见 get()

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

当未提供 section 时,返回一个 section_name, section_proxy 对的列表,包括 DEFAULTSECT。

否则,返回给定 section 中选项的 name, value 对的列表。可选参数的含义与 get() 方法相同。

在 3.8 版更改: vars 中存在的项不再出现在结果中。以前的行为将实际的解析器选项与为插值提供的变量混合在一起。

set(section, option, value)

如果给定的节存在,则将给定的选项设置为指定的值;否则引发 NoSectionErroroptionvalue 必须是字符串;如果不是,则引发 TypeError

write(fileobject, space_around_delimiters=True)

将配置的表示形式写入指定的文件对象,该对象必须以文本模式打开(接受字符串)。此表示形式可以被未来的 read() 调用解析。如果 space_around_delimiters 为 true,则键和值之间的分隔符将被空格包围。

在 3.14 版更改: 如果这将写入一个无法被该解析器未来的 read() 调用准确解析的表示形式,则会引发 InvalidWriteError。

备注

原始配置文件中的注释在写回配置时不会被保留。什么被视为注释,取决于为 comment_prefixinline_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_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_sectioninterpolation

在 3.5 版更改: 添加了 converters 参数。

在 3.8 版更改: 默认的 dict_typedict,因为它现在保留插入顺序。

在 3.13 版更改: 添加了 allow_unnamed_section 参数。

备注

请考虑使用 ConfigParser,它会检查要内部存储的值的类型。如果你不想要插值,可以使用 ConfigParser(interpolation=None)

add_section(section)

向实例添加一个名为 sectionUNNAMED_SECTION 的节。

如果给定的节已存在,则引发 DuplicateSectionError。如果传递了默认节名称,则引发 ValueError。如果传递了 UNNAMED_SECTION 且支持被禁用,则引发 UnnamedSectionDisabledError

section 的类型不会被检查,这允许用户创建非字符串名称的节区。 这种行为是不受支持的,并可能导致内部错误。

在 3.14 版本发生变更: 增加了对 UNNAMED_SECTION 的支持。

set(section, option, value)

如果给定的节区存在,则将给定的选项设置为指定的值;否则会引发 NoSectionError。 虽然可以使用 RawConfigParser(或将 raw 参数设为 true 的 ConfigParser)来内部存储非字符串值,但只有使用字符串值才能实现完整的功能(包括插值和输出到文件)。

该方法允许用户在内部为键分配非字符串值。这种行为是不受支持的,在尝试写入文件或以非原始模式获取时会导致错误。请使用映射协议 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 的子类。

exception configparser.InterpolationSyntaxError

当进行替换的源文本不符合所需语法时引发的异常。 InterpolationError 的子类。

exception configparser.MissingSectionHeaderError

在尝试解析一个没有节区头的文件时引发的异常。

exception configparser.ParsingError

在尝试解析文件时发生错误所引发的异常。

在 3.12 版本发生变更: 移除了 filename 属性和 __init__() 构造器参数。自 3.2 版起,它们已可通过名称 source 使用。

exception configparser.MultilineContinuationError

当一个没有对应值的键通过缩进的行进行续行时引发的异常。

在 3.13 版本加入。

exception configparser.UnnamedSectionDisabledError

在未启用 UNNAMED_SECTION 的情况下尝试使用它时引发的异常。

在 3.14 版本加入。

exception configparser.InvalidWriteError

当尝试的 ConfigParser.write() 操作在未来通过 ConfigParser.read() 调用时无法被准确解析时引发的异常。

例如:写入一个以 ConfigParser.SECTCRE 模式开头的键,在读取时会被解析为节区头。尝试写入此类内容将引发此异常。

在 3.14 版本加入。

脚注