configparser — 配置文件解析器 — Python 文档

来自菜鸟教程
Python/docs/3.7/library/configparser
跳转至:导航、​搜索

configparser — 配置文件解析器

源代码: :source:`Lib/configparser.py`



该模块提供了 ConfigParser 类,该类实现了一种基本配置语言,该语言提供的结构类似于 Microsoft Windows INI 文件中的结构。 您可以使用它来编写可由最终用户轻松定制的 Python 程序。

笔记

这个库不 不 解释或编写 INI 语法的 Windows 注册表扩展版本中使用的值类型前缀。


也可以看看

模块 shlex
支持创建类 Unix shell 的迷你语言,可用作应用程序配置文件的替代格式。
模块 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

由于这项任务非常普遍,配置解析器提供了一系列方便的 getter 方法来处理整数、浮点数和布尔值。 最后一个是最有趣的,因为简单地将值传递给 bool() 没有任何好处,因为 bool('False') 仍然是 True。 这就是配置解析器还提供 getboolean() 的原因。 此方法不区分大小写,可识别来自 'yes'/'no'、'on'/'off'、'true'/[ X123X] 和 '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)

在上面的示例中,ConfigParser 将 interpolation 设置为 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() 方法与映射协议和经典的 configparser API 都兼容。

  • parser.items() 与映射协议兼容(返回 section_name、section_proxy 对的列表,包括 DEFAULTSECT)。 但是,也可以使用参数调用此方法:parser.items(section, raw, vars)。 后一个调用返回指定 section 的 option、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'
  • 定界符,默认值:('=', ':')

    分隔符是将键与节中的值分隔开的子字符串。 一行中第一次出现定界子串被视为定界符。 这意味着值(但不是键)可以包含分隔符。

    另请参阅 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'

    这对于用户查看她是否使用比例字体来编辑文件来说尤其成问题。 这就是为什么当您的应用程序不需要空行值时,您应该考虑禁止它们。 这将使空行每次都拆分键。 在上面的例子中,它会产生两个键,key 和 this。

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

    允许其他部分或插值目的的默认值的特殊部分的约定是该库的一个强大概念,允许用户创建复杂的声明性配置。 此部分通常称为 "DEFAULT",但可以自定义以指向任何其他有效的部分名称。 一些典型值包括:"general" 或 "common"。 提供的名称用于在从任何源读取时识别默认部分,并在将配置写回文件时使用。 可以使用 parser_instance.default_section 属性检索其当前值,并且可以在运行时修改(即 将文件从一种格式转换为另一种格式)。

  • 插值,默认值:configparser.BasicInterpolation

    可以通过 interpolation 参数提供自定义处理程序来自定义插值行为。 None 可用于完全关闭插值,ExtendedInterpolation() 提供了受 zc.buildout 启发的更高级变体。 专用文档部分 中有关该主题的更多信息。 RawConfigParser 的默认值为 None。

  • 转换器,默认值:未设置

    配置解析器提供执行类型转换的选项值获取器。 默认情况下,实现了 getint()、getfloat() 和 getboolean()。 如果需要其他 getter,用户可以在子类中定义它们或传递一个字典,其中每个键是转换器的名称,每个值都是实现所述转换的可调用对象。 例如,传递 {'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

其他典型的布尔对包括 accept/reject 或 enabled/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_value 和 delimiters。


传统 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=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 时,它将用作在非空行中作为注释前缀的子字符串集。

当 strict 为 True(默认值)时,解析器在从单个源(文件、字符串或字典)读取时不允许任何节或选项重复,从而引发 DuplicateSectionError 或 DuplicateOptionError。 当 empty_lines_in_values 为 False(默认值:True)时,每个空行标记一个选项的结束。 否则,多行选项的内部空行将作为值的一部分保留。 当 allow_no_value 为 True(默认:False)时,接受没有值的选项; 为这些保留的值是 None 并且它们在没有尾随定界符的情况下被序列化。

当给出 default_section 时,它指定特殊部分的名称,该部分保存其他部分和插值目的的默认值(通常命名为 "DEFAULT")。 可以使用 default_section 实例属性在运行时检索和更改此值。

可以通过 interpolation 参数提供自定义处理程序来自定义插值行为。 None 可用于完全关闭插值,ExtendedInterpolation() 提供了受 zc.buildout 启发的更高级变体。 专用文档部分 中有关该主题的更多信息。

插值中使用的所有选项名称都将通过 optionxform() 方法传递,就像任何其他选项名称引用一样。 例如,使用 optionxform()(将选项名称转换为小写)的默认实现,值 foo %(bar)s 和 foo %(BAR)s 是等效的。

当给出 converters 时,它应该是一个字典,其中每个键代表类型转换器的名称,每个值都是一个可调用的,实现从字符串到所需数据类型的转换。 每个转换器在解析器对象和部分代理上都有自己对应的 get*() 方法。

3.1 版更改: 默认 dict_type 为 collections.OrderedDict。

在 3.2 版更改:allow_no_value、分隔符、comment_prefixes、strict、[X123_lines_XemptyX123X] , default_section 和 interpolation 添加。

3.5 版更改: 添加了 转换器 参数。

3.7 版更改:defaults 参数使用 read_dict() 读取,在整个解析器中提供一致的行为:非字符串键和值被隐式转换为字符串。

defaults()

返回一个包含实例范围默认值的字典。

sections()

返回可用部分的列表; 默认部分 未包含在列表中。

add_section(section)

将名为 section 的部分添加到实例。 如果给定名称的部分已经存在,则会引发 DuplicateSectionError。 如果传递了 default section 名称,则会引发 ValueError。 该部分的名称必须是一个字符串; 如果不是,则引发 TypeError。

3.2 版更改: 非字符串部分名称引发 TypeError。

has_section(section)

指示命名的 部分 是否存在于配置中。 默认部分未被确认。

options(section)

返回指定的 部分 中可用的选项列表。

has_option(section, option)

如果给定的 section 存在,并且包含给定的 option,则返回 True; 否则返回 False。 如果指定的 section 是 None 或空字符串,则假定为 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 读取和解析配置数据,它必须是一个可迭代的产生 Unicode 字符串(例如以文本模式打开的文件)。

可选参数 source 指定正在读取的文件的名称。 如果未给出且 f 具有 name 属性,则用于 source; 默认值为 '<???>'。

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

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

从字符串解析配置数据。

可选参数 source 指定传递的字符串的上下文特定名称。 如果未给出,则使用 '<string>'。 这通常应该是文件系统路径或 URL。

3.2 版中的新功能。

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

从提供类似 dict 的 items() 方法的任何对象加载配置。 键是部分名称,值是字典,其中包含应该出现在该部分中的键和值。 如果使用的字典类型保留顺序,则部分及其键将按顺序添加。 值会自动转换为字符串。

可选参数 source 指定传递的字典的上下文特定名称。 如果未给出,则使用 <dict>。

此方法可用于在解析器之间复制状态。

3.2 版中的新功能。

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

为命名的 部分 获取 选项 值。 如果提供了 vars,它必须是一个字典。 option 在 vars(如果提供)、section 和 DEFAULTSECT 中按该顺序查找。 如果未找到密钥并且提供了 fallback,则将其用作回退值。 None 可以作为 回退 值提供。

所有 '%' 插值都在返回值中展开,除非 raw 参数为真。 以与选项相同的方式查找插值键的值。

3.2 版更改: 参数 raw、vars 和 fallback 仅是关键字,以保护用户不会尝试使用第三个参数作为fallback fallback(尤其是在使用映射协议时)。

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

将指定的 部分 中的 选项 强制为整数的便捷方法。 有关 raw、vars 和 fallback 的解释,请参见 get()。

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

将指定的 部分 中的 选项 强制转换为浮点数的便捷方法。 有关 raw、vars 和 fallback 的解释,请参见 get()。

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

将指定 部分 中的 选项 强制为布尔值的便捷方法。 请注意,该选项的可接受值为 '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_name、section_proxy 对的列表,包括 DEFAULTSECT。

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

set(section, option, value)

如果给定部分存在,则将给定选项设置为指定值; 否则引发 NoSectionError。 option 和 value 必须是字符串; 如果不是,则引发 TypeError。

write(fileobject, space_around_delimiters=True)

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

remove_option(section, option)

从指定的 节 中删除指定的 选项 。 如果该部分不存在,则引发 NoSectionError。 如果存在要删除的选项,则返回 True; 否则返回 False。

remove_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.read_file(readline_generator(fp)) 代替 parser.readfp(fp)。

configparser.MAX_INTERPOLATION_DEPTH
当 raw 参数为 false 时,get() 递归插值的最大深度。 这仅在使用默认 插值 时才相关。


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_section 和 set 方法以及旧的 defaults= 关键字使用非字符串部分名称、选项名称和值参数处理。

笔记

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

add_section(section)

将名为 section 的部分添加到实例。 如果给定名称的部分已经存在,则会引发 DuplicateSectionError。 如果传递了 default section 名称,则会引发 ValueError。

未选中 section 的类型,这允许用户创建非字符串命名的节。 此行为不受支持,可能会导致内部错误。

set(section, option, value)

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

此方法允许用户在内部为键分配非字符串值。 此行为不受支持,并且在尝试写入文件或以非原始模式获取文件时会导致错误。 使用不允许进行此类分配的映射协议 API。


例外

exception configparser.Error
所有其他 configparser 例外的基类。
exception configparser.NoSectionError
未找到指定部分时引发异常。
exception configparser.DuplicateSectionError

如果 add_section() 使用已经存在的节的名称或在严格解析器中的名称调用,如果在单个输入文件、字符串或字典中找到多个节,则会引发异常。

3.2 版新功能:添加了 可选的 source 和 lineno 属性和参数 __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,[ X67X]7,8,9,10)
配置解析器允许大量定制。 如果您有兴趣更改脚注参考中概述的行为,请参阅 自定义解析器行为 部分。