14.2. configparser - 配置文件解析器

源代码: Lib / configparser.py

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

注意

此库 解释或写入在Windows注册表扩展版本的INI语法中使用的值类型前缀。

也可以看看

模块shlex
支持创建的Unix shell样微型语言,可以用作应用程序配置文件的备用格式。
模块json
json模块实现了JavaScript语法的一个子集,也可以用于此目的。

14.2.1. 快速启动

让我们来看一个非常基本的配置文件,如下所示:

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

正如你所看到的,我们可以把一个配置解析器看作一个字典。这里有所区别,稍后概述,但是行为非常接近您从字典中期望的行为。

现在我们已经创建并保存了一个配置文件,让我们从文件中读取和查看所拥有的数据。

>>> import configparser
>>> 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]存储。

14.2.2. 支持的数据类型

Config解析器不会猜测配置文件中的值的数据类型,始终将它们作为字符串存储在内部。这意味着如果你需要其他数据类型,你应该自己转换:

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

由于这个任务很常见,config解析器提供了一系列方便的getter方法来处理整数,浮点数和布尔值。最后一个是最有趣的,因为只是将值传递给bool()将没有什么好的,因为bool('False')仍然是True这就是为什么config解析器也提供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] T0>

14.2.3. 回退值

与字典一样,您可以使用节的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

14.2.4. 支持的INI文件结构

A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default [1]). 默认情况下,节名称区分大小写,但键不是[1]前导和尾随空格将从键和值中删除。可以省略值,在这种情况下,键/值分隔符也可以省略。值也可以跨越多行,只要它们缩进得比值的第一行更深。根据解析器的模式,空白行可能被视为多行值的部分或被忽略。

配置文件可以包括以特定字符(#;,默认为[1])作为前缀的注释。注释可以自己出现在空行上,可能缩进。 [1] T0>

例如:

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

14.2.5. 插值

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

class configparser.BasicInterpolation

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

例如:

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

在上面的示例中,将ConfigParser插值设置为BasicInterpolation()会将%(home_dir)shome_dir(在这种情况下为/Users)。%(my_dir)s实际上会解析为/Users/lumberjack所有内插均按需完成,因此引用链中使用的键不必在配置文件中以任何特定顺序指定。

With interpolation set to None, the parser would simply return %(my_dir)s/Pictures as the value of my_pictures and %(home_dir)s/lumberjack as the value of my_dir.

class configparser.ExtendedInterpolation

用于实现更高级语法的插值替代处理程序,用于zc.buildout中的实例。扩展插值使用${section:option}表示来自外部节的值。插值可以跨越多个级别。为方便起见,如果省略了section:部分,则内插默认为当前部分(可能为特殊部分的默认值)。

例如,上面用基本插值指定的配置,在扩展插值中看起来像这样:

[Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures

还可以获取来自其他部分的值:

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

14.2.6. 映射协议访问

版本3.2中的新功能。

映射协议访问是功能的通用名称,它允许使用自定义对象,就像它们是字典一样。configparser的情况下,映射接口实现使用parser['section']['option']符号。

parser['section']特别是在解析器中返回该节的数据的代理。这意味着不会复制这些值,但是它们是根据需要从原始解析器获取的。更重要的是,当值在段代理上改变时,它们实际上在原始解析器中被改变。

configparser对象的行为尽可能接近实际字典。映射界面已完成,并且符合MutableMapping ABC。但是,还有一些差异应该考虑:

  • 默认情况下,部分中的所有键都可以以不区分大小写的方式访问[1]例如。for option in parser["section"] yields only optionxform‘ed option key names. 这意味着默认情况下较低级的键。同时,对于保存键'a'的部分,这两个表达式返回True

    "a" in parser["section"]
    "A" in parser["section"]
    
  • 所有部分都包含DEFAULTSECT值,这意味着.clear()可能不会将该部分留空。这是因为默认值不能从节中删除(因为在技术上它们不在那里)。如果它们在部分中被覆盖,则删除导致默认值再次可见。试图删除默认值会导致一个KeyError

  • DEFAULTSECT无法从解析器中移除:

    • 试图删除它引发ValueError
    • parser.clear()保持原样,
    • parser.popitem()从不返回。
  • parser.get(section, option, ** kwargs) - 第二个参数是/ t4>回退值。但请注意,区段级get()方法与映射协议和经典的configparser API兼容。

  • parser.items()与映射协议兼容(返回包含DEFAULTSECT的section_namesection_proxy对的列表)。但是,此方法也可以使用参数调用:parser.items(section, raw, vars)后一个调用返回指定section选项对的列表,其中所有内插展开(除非raw=True

映射协议在现有的遗留API之上实现,以便覆盖原始接口的子类仍然应该具有按预期工作的映射。

14.2.7. 自定义解析器行为

有几乎和使用它的应用程序一样多的INI格式变体。configparser很大程度上为最大的可用的INI样式集提供支持。默认功能主要由历史背景决定,很有可能您想要自定义一些功能。

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

  • 默认值,默认值:None

    此选项接受键值对的字典,该字典将最初放在DEFAULT部分中。这使得一种优雅的方式来支持不指定与记录的默认值相同的值的简明配置文件。

    提示:如果要为特定段指定默认值,请在读取实际文件之前使用read_dict()

  • dict_type,默认值:collections.OrderedDict

    此选项对映射协议的行为以及写入配置文件的外观有重大影响。使用默认有序字典,每个部分按它们添加到解析器的顺序存储。部分中的选项也是如此。

    可以使用替代字典类型来例如对回写上的段和选项进行排序。出于性能原因,您还可以使用常规字典。

    请注意:有一些方法可以在单个操作中添加一组键值对。当在这些操作中使用常规字典时,键的顺序可以是随机的。例如:

    >>> 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()
    ['section3', 'section2', 'section1']
    >>> [option for option in parser['section3']]
    ['baz', 'foo', 'bar']
    

    在这些操作中,您还需要使用有序字典:

    >>> from collections import OrderedDict
    >>> parser = configparser.ConfigParser()
    >>> parser.read_dict(
    ...   OrderedDict((
    ...     ('s1',
    ...      OrderedDict((
    ...        ('1', '2'),
    ...        ('3', '4'),
    ...        ('5', '6'),
    ...      ))
    ...     ),
    ...     ('s2',
    ...      OrderedDict((
    ...        ('a', 'b'),
    ...        ('c', 'd'),
    ...        ('e', 'f'),
    ...      ))
    ...     ),
    ...   ))
    ... )
    >>> parser.sections()
    ['s1', 's2']
    >>> [option for option in parser['s1']]
    ['1', '3', '5']
    >>> [option for option in parser['s2'].values()]
    ['b', 'd', 'f']
    
  • 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
    
  • 严格,默认值:True

    When set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or 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属性来检索,并且可以在运行时被修改。将文件从一种格式转换为另一种格式)。

  • 插值,默认值:configparser.BasicInterpolation

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

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

    Config解析器提供执行类型转换的选项值getter。默认情况下,实现getint()getfloat()getboolean()如果需要其他getter,用户可以在子类中定义它们,或者传递一个字典,其中每个键是转换器的名称,每个值是一个可调用的实现所述转换。对于实例,传递{'decimal': decimal.Decimal}会将getdecimal()换句话说,可以同时写入parser_instance.getdecimal('section', 'key', fallback = 0) t3 >parser_instance ['section']。getdecimal('key', 0)

    如果转换器需要访问解析器的状态,它可以被实现为配置解析器子类上的方法。如果此方法的名称以get开头,它将在所有段代理上以dict兼容的形式提供(参见上面的getdecimal()示例)。

更高级的定制可以通过覆盖这些解析器属性的默认值来实现。默认值是在类上定义的,因此它们可能被子类或属性赋值重写。

configparser.BOOLEAN_STATES

By default when using getboolean(), config parsers consider the following values True: '1', 'yes', 'true', 'on' and the following values 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']
configparser.SECTCRE

用于解析节头的编译正则表达式。默认匹配[section]到名称"section"Whitespace is considered part of the section name, thus [ larch ] will be read as a section of name " larch ". 如果此属性不适用,则覆盖此属性。例如:

>>> config = """
... [Section 1]
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> typical = ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', '  Section 2  ']
>>> custom = ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']

注意

虽然ConfigParser对象也使用OPTCRE属性来识别选项行,但不建议覆盖它,因为这会干扰构造函数选项allow_no_value分隔符

14.2.8. 旧版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!"

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

主配置解析器。当给定默认值时,它被初始化为内部默认值的字典。当给定dict_type时,它将用于为节列表,节中的选项和默认值创建字典对象。

当给定分隔符时,它用作将键与值分隔开的子串集合。当给定comment_prefixes时,它将用作前缀为空的行中的注释的子串集合。注释可以缩进。当给定inline_comment_prefixes时,它将用作非空行中的注释前面的子字符集。

strictTrue(默认值)时,解析器将不允许从单个源(文件,字符串或字典)读取任何节或选项重复, DuplicateSectionErrorDuplicateOptionErrorempty_lines_in_valuesFalse(默认值:True)时,每个空行标记选项的结尾。否则,多行选项的内部空行将保留为值的一部分。allow_no_valueTrue(默认值:False)时,接受不带值的选项;为它们保留的值为None,它们被序列化,没有尾部分隔符。

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

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

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

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

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

在版本3.2中更改: allow_no_value分隔符comment_prefixes严格 empty_lines_in_valuesdefault_section插值

在版本3.5中已更改:添加了转换器参数。

defaults()

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

sections()

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

add_section(section)

在实例中添加一个名为的部分如果给定名称的段已经存在,则会引发DuplicateSectionError如果传递默认部分名称,则会引发ValueError节的名称必须是字符串;如果不是,则引发TypeError

在版本3.2中更改:非字符串段名称引发TypeError

has_section(section)

指示配置中是否存在名为默认部分未确认。

options(section)

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

has_option(section, option)

如果给定的存在,并且包含给定的选项,则返回True;否则返回False如果指定的None或空字符串,则假定为DEFAULT。

read(filenames, encoding=None)

尝试读取和解析文件名列表,返回已成功解析的文件名列表。如果文件名是字符串,则将其视为单个文件名。如果无法打开文件名中命名的文件,该文件将被忽略。这是为了能够指定潜在的配置文件位置列表(例如,当前目录,用户的主目录和一些系统范围的目录),并且将读取列表中的所有现有配置文件。如果没有命名文件存在,则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中的新功能: 编码参数。以前,使用open()的默认编码读取所有文件。

read_file(f, source=None)

f读取并解析配置数据,该数据必须是可迭代的,以生成Unicode字符串(例如以文本模式打开的文件)。

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

版本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,它必须是字典。vars(如果提供),DEFAULTSECT中按顺序查找选项如果未找到键且提供fallback,则将其用作回退值。None可以作为回退值提供。

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

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

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

一种方便的方法,将指定的中的选项强制为整数。有关rawvarsfallback的说明,请参阅get()

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

一种方便的方法,将指定的中的选项强制为浮点数。有关rawvarsfallback的说明,请参阅get()

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

一种方便的方法,用于将指定的中的选项强制为布尔值。Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. 这些字符串值以不区分大小写的方式进行检查。任何其他值将导致它引发ValueError有关rawvarsfallback的说明,请参阅get()

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

当未提供时,返回section_namesection_proxy对的列表,包括DEFAULTSECT。

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

在版本3.2中更改: vars中显示的项目不再显示在结果中。之前的行为将实际解析器选项与为插值提供的变量混合。

set(section, option, value)

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

write(fileobject, space_around_delimiters=True)

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

remove_option(section, option)

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

remove_section(section)

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

optionxform(option)

将在输入文件中找到的或由客户端代码传递的选项名称选项转换为应在内部结构中使用的形式。默认实现返回选项的小写版本;子类可以覆盖此或客户端代码可以在实例上设置此名称的属性以影响此行为。

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

cfgparser = ConfigParser()
cfgparser.optionxform = str

请注意,当读取配置文件时,在调用optionxform()之前,选项名称周围的空格被去除。

readfp(fp, filename=None)

自版本3.2后已弃用:改用read_file()

在版本3.2中更改: readfp()现在在f上迭代,而不是调用f.readline()

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

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

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

configparser。 T0> MAX_INTERPOLATION_DEPTH T1> ¶ T2>

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

14.2.10. 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_sectionset方法。

注意

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

add_section(section)

在实例中添加一个名为的部分如果给定名称的段已经存在,则会引发DuplicateSectionError如果传递默认部分名称,则会引发ValueError

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

set(section, option, value)

如果给定段存在,则将给定选项设置为指定值;否则引发NoSectionError虽然RawConfigParser(或ConfigParserraw参数设置为true)可用于内部字符串值,完整功能(包括插值和文件输出)只能使用字符串值来实现。

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

14.2.11. 例外¶ T0>

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) Config parsers allow for heavy customization. 如果您有兴趣更改脚注参考中概述的行为,请参阅自定义解析器行为部分。