configparser ---配置文件分析器

源代码: Lib/configparser.py


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

注解

这个类库有 not 解释或写入Windows注册表扩展版ini语法中使用的值类型前缀。

参见

模块 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文件的结构 in the following section . 基本上,文件由部分组成,每个部分都包含带有值的键。 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)
...

正如您所看到的,我们可以像对待字典一样对待配置解析器。有区别, outlined later 但这种行为与你从字典中所期望的非常接近。

既然我们已经创建并保存了一个配置文件,那么让我们把它读回并研究它所保存的数据。

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

可以将多个配置读入一个 ConfigParser ,其中最近添加的配置具有最高优先级。任何冲突的密钥都将从较新的配置中获取,而先前存在的密钥将被保留。

>>> another_config = configparser.ConfigParser()
>>> another_config.read('example.ini')
['example.ini']
>>> another_config['topsecret.server.com']['Port']
'50022'
>>> another_config.read_string("[topsecret.server.com]\nPort=48484")
>>> another_config['topsecret.server.com']['Port']
'48484'
>>> another_config.read_dict({"topsecret.server.com": {"Port": 21212}})
>>> another_config['topsecret.server.com']['Port']
'21212'
>>> another_config['topsecret.server.com']['ForwardX11']
'no'

这种行为相当于 ConfigParser.read() 将多个文件传递给 文件名 参数。

支持的数据类型

配置分析器不猜测配置文件中的值的数据类型,总是将它们作为字符串存储在内部。这意味着,如果需要其他数据类型,则应自行转换:

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

由于此任务非常常见,配置解析器提供了一系列方便的getter方法来处理整数、浮点数和布尔值。最后一个是最有趣的,因为只需将值传递给 bool() would do no good since bool('False') is still True. This is why config parsers also provide getboolean(). This method is case-insensitive and recognizes Boolean values from 'yes'/'no''on'/'off''true'/'false''1'/'0' 1. 例如:

>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True

除了 getboolean() ,配置解析器也提供等效的 getint()getfloat() 方法。您可以注册自己的转换器并自定义提供的转换器。 1

回退值

与字典一样,您可以使用节的 get() 提供回退值的方法:

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

请注意,默认值优先于回退值。例如,在我们的示例中, 'CompressionLevel' 仅在中指定了密钥 'DEFAULT' 部分。如果我们试着从这个部门得到它 'topsecret.server.com' ,我们将始终获得默认值,即使我们指定了回退:

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

还有一件事要注意,解析器级别 get() 方法提供了一个自定义的、更复杂的接口,为了向后兼容而进行维护。使用此方法时,可以通过 fallback 仅关键字参数:

>>> config.get('bitbucket.org', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'

相同的 fallback 参数不能与 getint()getfloat()getboolean() 方法,例如:

>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False

支持的ini文件结构

配置文件由节组成,每个节由一个 [section] 标题,后跟由特定字符串分隔的键/值条目 (=: 默认情况下 1) . 默认情况下,节名称区分大小写,但键不区分大小写 1. 从键和值中删除前导空格和尾随空格。可以省略值,在这种情况下,键/值分隔符也可以省略。值也可以跨多行,只要它们的缩进深度大于值的第一行。根据解析器的模式,可以将空行视为多行值的一部分或忽略。

配置文件可以包含注释,前缀为特定字符 (#; 默认情况下 1) . 注释可能单独出现在一个空行上,也可能缩进。 1

例如:

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?

值的插值

在核心功能之上, ConfigParser 支持插值。这意味着在返回值之前可以对其进行预处理 get() 调用。

class configparser.BasicInterpolation

使用的默认实现 ConfigParser . 它允许值包含引用同一节中其他值或特殊默认节中的值的格式字符串。 1. 初始化时可以提供其他默认值。

例如:

[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

[Escape]
gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)

在上面的例子中, 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 新版功能.

mapping protocol access是一个通用的功能名称,它可以像使用字典一样使用自定义对象。万一 configparser ,映射接口实现正在使用 parser['section']['option'] 表示法。

parser['section'] 尤其是在解析器中返回该节数据的代理。这意味着不会复制这些值,但它们是根据需要从原始解析器中提取的。更重要的是,当节代理服务器上的值发生变化时,它们实际上在原始的解析器中发生了变化。

configparser 对象的行为尽可能接近实际字典。映射接口是完整的,并依附于 MutableMapping 抽象基类但是,应考虑到一些差异:

  • 默认情况下,可以以不区分大小写的方式访问节中的所有键 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) -第二个参数是 not 回退值。但是请注意,节级别 get() 方法与映射协议和经典的ConfigParser API都兼容。

  • parser.items() 与映射协议兼容(返回 section_namesection_proxy 包括defaultsect在内的对)。但是,也可以使用以下参数调用此方法: parser.items(section, raw, vars) .后一个调用返回 optionvalue 对指定的 section ,所有插值都展开(除非 raw=True 提供)。

映射协议是在现有遗留API的基础上实现的,因此覆盖原始接口的子类仍应具有预期的工作映射。

自定义分析器行为

有几乎与使用它的应用程序一样多的ini格式变体。 configparser 很长一段时间来支持可用的最大的、合理的ini样式集。默认功能主要由历史背景决定,您很可能希望自定义一些功能。

更改特定配置解析器工作方式的最常见方法是使用 __init__() 选项:

  • 默认值 ,默认值: 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 ,默认值: ('=', ':')

    分隔符是从节中的值分隔键的子字符串。行上第一个出现的分隔子字符串被视为分隔符。这意味着值(而不是键)可以包含分隔符。

    也见 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
    
  • 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 . 关于主题的更多信息 dedicated documentation section . RawConfigParser 默认值为 None .

  • converters ,默认值:未设置

    配置分析器提供执行类型转换的选项值获取器。默认情况下 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/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有时更高级、低级别和完全违反直觉。

写入配置文件的示例:

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

默认值在这两种类型的配置arser中都可用。如果在其他地方未定义所使用的选项,则在插值中使用它们。地址:

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

主配置分析器。什么时候? 默认值 它被初始化为内部默认值字典。什么时候? 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 . 关于主题的更多信息 dedicated documentation section .

所有用于插值的选项名称都将通过 optionxform() 方法与任何其他选项名引用一样。例如,使用 optionxform() (它将选项名转换为小写),值 foo %(bar)sfoo %(BAR)s 是等价的。

什么时候? converters 如果给定,则应该是一个字典,其中每个键表示类型转换器的名称,每个值是可调用的,实现从字符串到所需数据类型的转换。每个转换器都有自己的对应 get*() 解析器对象和节代理上的方法。

在 3.1 版更改: 默认值 dict_typecollections.OrderedDict .

在 3.2 版更改: allow_no_valuedelimiterscomment_prefixesstrictempty_lines_in_valuesdefault_sectioninterpolation 加入。

在 3.5 版更改: 这个 converters 已添加参数。

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

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

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 或者为空字符串,则假定为默认值。

read(filenames, encoding=None)

尝试读取和分析文件名的iterable,返回成功分析的文件名列表。

如果 filename 是一个字符串 bytes 对象或 path-like object ,它被视为单个文件名。如果文件名为 filename 无法打开,该文件将被忽略。这是为了让您可以指定潜在配置文件位置的iterable(例如,当前目录、用户的主目录和一些系统范围的目录),并且将读取iterable中的所有现有配置文件。

如果不存在任何命名文件,则 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 新版功能: 这个 encoding 参数。以前,所有文件都是使用默认编码读取的 open() .

3.6.1 新版功能: 这个 filename 参数接受 path-like object .

3.7 新版功能: 这个 filename 参数接受 bytes 对象。

read_file(f, source=None)

从中读取和分析配置数据 f 它必须是可生成Unicode字符串的iterable(例如以文本模式打开的文件)。

可选参数 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])

得到一个 option 名称的值 section . 如果 vars 提供,必须是字典。这个 option 被抬高 vars (如果提供) sectionDEFAULTSECT 按这个顺序。如果找不到钥匙, fallback 提供了,它用作回退值。 None 可作为 fallback 价值。

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

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

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

一种方便的方法,它强制 option 在指定的 section 变为整数。见 get() 解释 rawvarsfallback .

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

一种方便的方法,它强制 option 在指定的 section 浮点数。见 get() 解释 rawvarsfallback .

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

一种方便的方法,它强制 option 在指定的 section 一个布尔值。请注意,选项的接受值为 '1''yes''true''on' ,导致此方法返回 True'0''no''false''off' 使它返回 False . 以不区分大小写的方式检查这些字符串值。任何其他值都会使其上升 ValueError . 见 get() 解释 rawvarsfallback .

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

什么时候? section 未给出,返回 section_namesection_proxy 对,包括defaultsect。

否则,返回 namevalue 给定选项的对 section . 可选参数的含义与 get() 方法。

在 3.8 版更改: 存在于中的项 vars 结果中不再出现。前面的行为混合了实际的解析器选项和为插值提供的变量。

set(section, option, value)

如果给定节存在,则将给定选项设置为指定值;否则将引发 NoSectionError . optionvalue 必须是字符串;如果不是, TypeError 提高了。

write(fileobject, space_around_delimiters=True)

将配置的表示形式写入指定的 file object ,必须在文本模式下打开(接受字符串)。这种表示可以由未来分析 read() 调用。如果 space_around_delimiters 为true,键和值之间的分隔符由空格包围。

remove_option(section, option)

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

remove_section(section)

删除指定的 section 从配置中。如果该部分实际上存在,则返回 True . 否则返回 False .

optionxform(option)

转换选项名称 option 在输入文件中找到或由客户机代码传入内部结构中应该使用的表单。默认实现返回的小写版本 option ;子类可以重写此属性,或者客户机代码可以在实例上设置此名称的属性以影响此行为。

您不需要子类化解析器来使用这个方法,也可以在实例上将它设置为接受字符串参数并返回字符串的函数。设置为 str 例如,将使选项名称区分大小写:

cfgparser = ConfigParser()
cfgparser.optionxform = str

请注意,在读取配置文件时,选项名周围的空白将在 optionxform() 被称为。

readfp(fp, filename=None)

3.2 版后已移除: 使用 read_file() 相反。

在 3.2 版更改: readfp() 现在迭代 fp 而不是调用 fp.readline() .

用于现有代码调用 readfp() 对于不支持迭代的参数,以下生成器可以用作类似文件的对象的封装器:

def readline_generator(fp):
    line = fp.readline()
    while line:
        yield line
        line = fp.readline()

而不是 parser.readfp(fp) 使用 parser.read_file(readline_generator(fp)) .

configparser.MAX_INTERPOLATION_DEPTH

递归插值的最大深度 get()raw 参数为假。仅当默认值为 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])

的传统变体 ConfigParser . 默认情况下,它禁用了插值,并允许通过其不安全项使用非字符串节名称、选项名称和值。 add_sectionset 方法以及遗产 defaults= 关键字参数处理。

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

注解

考虑使用 ConfigParser 而是检查要在内部存储的值的类型。如果不需要插值,可以使用 ConfigParser(interpolation=None) .

add_section(section)

添加名为的节 section 到实例。如果已存在具有给定名称的节, DuplicateSectionError 提高了。如果 缺省部分 名称已通过, ValueError 提高了。

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

set(section, option, value)

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

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

例外情况

exception configparser.Error

所有其他的基类 configparser 例外情况。

exception configparser.NoSectionError

找不到指定节时引发异常。

exception configparser.DuplicateSectionError

在以下情况下引发异常 add_section() 当在单个输入文件、字符串或字典中发现某个节多次时,使用已存在的节的名称或在严格的分析器中调用该节。

3.2 新版功能: 可选的 sourcelineno 属性和参数 __init__() 加入。

exception configparser.DuplicateOptionError

如果在从单个文件、字符串或字典读取过程中出现两次单个选项,则由严格的分析器引发异常。这会捕获拼写错误和与大小写敏感度相关的错误,例如,字典可能有两个表示同一不区分大小写配置键的键。

exception configparser.NoOptionError

在指定的节中找不到指定选项时引发异常。

exception configparser.InterpolationError

执行字符串插值时出现问题时引发异常的基类。

exception configparser.InterpolationDepthError

由于迭代次数超过,字符串插值无法完成时引发异常 MAX_INTERPOLATION_DEPTH .的子类 InterpolationError .

exception configparser.InterpolationMissingOptionError

从值引用的选项不存在时引发异常。的子类 InterpolationError .

exception configparser.InterpolationSyntaxError

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

exception configparser.MissingSectionHeaderError

试图分析没有节头的文件时引发异常。

exception configparser.ParsingError

尝试分析文件时发生错误时引发异常。

在 3.2 版更改: 这个 filename 属性与 __init__() 参数已重命名为 source 为了一致性。

脚注

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

配置分析器允许大量定制。如果您有兴趣更改脚注参考中列出的行为,请参考 Customizing Parser Behaviour 部分。