python / 3.7.2rc1 / all / library-configparser.html

configparser —配置文件解析器

源代码: Lib/configparser.py


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

Note

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

See also

  • Module shlex

  • 支持创建类似 Unix Shell 的迷你语言,可用作应用程序配置文件的替代格式。

  • Module json

  • json 模块实现了 JavaScript 语法的子集,也可以用于此目的。

Quick Start

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

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

如您所见,我们可以像对待字典一样对待配置解析器。两者之间存在差异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]中。

Supported Datatypes

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

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

由于此任务非常常见,因此配置解析器提供了一系列方便的 getter 方法来处理整数,浮点数和布尔值。最后一个是最有趣的,因为仅将值传递给bool()就没有用,因为bool('False')仍然是True。这就是配置解析器还提供getboolean()的原因。此方法不区分大小写,并且从'yes'/'no''on'/'off''true'/'false''1'/'0' [1]识别布尔值。例如:

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

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

Fallback Values

与字典一样,您可以使用部分的get()方法来提供后备值:

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

请注意,默认值优先于后备值。例如,在我们的示例中,仅在'DEFAULT'部分中指定了'CompressionLevel'键。如果我们try从'topsecret.server.com'部分获取它,即使我们指定了备用广告,我们也将始终使用默认值:

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

还有一点需要注意的是,解析器级别的get()方法提供了一个自定义,更复杂的接口,该接口被维护以实现向后兼容。使用此方法时,可以passfallback仅关键字参数提供回退值:

>>> 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]Headers 开头,后跟由特定字符串(默认为__ =:)分隔的键/值条目。默认情况下,节名称区分大小写,但键不[1]。前导和尾随空格从键和值中删除。可以Ellipsis值,在这种情况下,键/值定界符也可以省去。值也可以跨多行,只要它们缩进得比值的第一行深。根据解析器的模式,空白行可能被视为多行值的一部分或被忽略。

配置文件可能包含 Comments,并带有特定字符(默认为#;)作为前缀。Comments 可能会自己出现在否则为空的行上,可能会缩进。 [1]

For example:

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

值插值

在核心Function之上,ConfigParser支持插值。这意味着可以对值进行预处理,然后再从get()调用中返回它们。

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

For example:

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

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

interpolation设置为None,解析器将简单地返回%(my_dir)s/Pictures作为my_pictures的值和%(home_dir)s/lumberjack作为my_dir的值。

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

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

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

Map 协议访问

3.2 版中的新Function。

Map 协议访问是Function的通用名称,该Function使自定义对象可以像字典一样使用。在configparser的情况下,Map 接口实现使用parser['section']['option']表示法。

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

configparser个对象的行为尽可能接近实际的字典。Map 界面已完成,并遵循MutableMapping ABC。但是,应考虑一些差异:

  • 默认情况下,可以使用不区分大小写的方式[1]来访问节中的所有键。例如。 for option in parser["section"]仅产生optionxform'ed 选项键名称。这意味着默认情况下小写的键。同时,对于包含键'a'的部分,两个表达式都返回True
"a" in parser["section"]
"A" in parser["section"]
  • 所有节也都包含DEFAULTSECT值,这意味着节上的.clear()可能不会使该节明显为空。这是因为无法从该部分中删除默认值(因为从技术上讲它们不存在)。如果它们在本节中被覆盖,则删除将使默认值再次可见。try删除默认值会导致KeyError

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

  • try删除它会引发ValueError

    • parser.clear()保持原样,

    • parser.popitem()永不返回。

  • parser.get(section, option, **kwargs)-第二个参数不是回退值。但是请注意,节级别的get()方法与 Map 协议和经典的 configparser API 都兼容。

  • parser.items()与 Map 协议兼容(返回* section_name section_proxy 对的列表,包括 DEFAULTSECT)。但是,也可以使用参数parser.items(section, raw, vars)来调用此方法。后面的调用返回指定section option value *对的列表,并扩展了所有插值(除非提供raw=True)。

Map 协议是在现有旧版 API 之上实现的,因此,覆盖原始接口的子类仍应按预期工作。

自定义解析器行为

INI 格式变体几乎与使用它的应用程序一样多。 configparser为提供最大的可用 INI 样式集提供了大力支持。默认Function主要由历史背景决定,很可能您希望自定义某些Function。

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

    • defaults *,默认值:None

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

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

    • dict_type *,默认值:dict

此选项对 Map 协议的行为以及书面配置文件的外观有重大影响。使用标准字典,每个部分都按照它们添加到解析器中的 Sequences 进行存储。部分中的选项也是如此。

例如,可以使用备用字典类型对写回时的节和选项进行排序。

请注意:有多种方法可以在单个操作中添加一组键值对。当您在这些操作中使用常规词典时,键的 Sequences 将被排序。例如:

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

Comments 前缀是指示配置文件中有效 Comments 开始的字符串。 * comment_prefixes 仅用于否则为空的行(可选缩进),而 inline_comment_prefixes *可以在每个有效值之后使用(例如节名,选项和空行)。默认情况下,禁用内联 Comments,并且'#'';'用作整行 Comments 的前缀。

在版本 3.2 中更改:在configparser的先前版本中,行为与comment_prefixes=('#',';')inline_comment_prefixes=(';',)相匹配。

请注意,配置解析器不支持转义 Comments 前缀,因此使用* inline_comment_prefixes 可能会阻止用户使用用作 Comments 前缀的字符来指定选项值。如有疑问,请避免设置 inline_comment_prefixes *。在任何情况下,在多行值的行首存储 Comments 前缀字符的唯一方法是对前缀进行插值,例如:

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

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

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

配置解析器提供执行类型转换的选项值获取器。默认情况下,实现getint()getfloat()getboolean()。如果需要其他获取器,则用户可以在子类中定义它们或pass字典,其中每个键是转换器的名称,每个值是实现所述转换的可调用项。例如,传递{'decimal': decimal.Decimal}将在解析器对象和所有节代理两者上添加getdecimal()。换句话说,可以同时写入parser_instance.getdecimal('section', 'key', fallback=0)parser_instance['section'].getdecimal('key', 0)

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

pass覆盖这些解析器属性的默认值,可以实现更高级的自定义。默认值是在类上定义的,因此它们可能会被子类或属性分配所覆盖。

  • ConfigParser. BOOLEAN_STATES
    • 默认情况下,使用getboolean()时,配置解析器考虑以下值True'1''yes''true''on'和以下值False'0''no''false''off'。您可以pass指定一个自定义的字符串字典及其布尔结果来覆盖它。例如:
>>> 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']

Note

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']

Note

尽管 ConfigParser 对象还使用OPTCRE属性来识别选项行,但不建议覆盖它,因为这会干扰构造函数选项* allow_no_value delimiters *。

旧版 API 范例

主要是出于向后兼容性的考虑,configparser还提供了具有显式get/set方法的旧版 API。尽管存在以下概述的方法的有效用例,但对于新项目,首选 Map 协议访问。遗留 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 Objects

    • 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 ={} *)
    • 主要配置解析器。当给出* defaults 时,它被初始化为固有默认字典。给出 dict_type *时,它将用于为节列表,节中的选项以及默认值创建字典对象。

给定* delimiters 时,它用作将键与值分隔开的子字符串集。给定 comment_prefixes 时,它将用作子字符串集,这些子字符串在否则为空的行中添加 Comments 前缀。Comments 可以缩进。如果指定 inline_comment_prefixes *,它将用作在非空行中添加 Comments 前缀的子字符串集。

当* strict True(默认值)时,解析器从单个来源(文件,字符串或字典)读取时,不允许任何节或选项重复,并提高DuplicateSectionErrorDuplicateOptionError。当 empty_lines_in_values False(默认值:True)时,每个空行都标记选项的结尾。否则,多行选项的内部空行将保留为值的一部分。当 allow_no_value *为True(默认值:False)时,接受不带值的选项;否则为 0.它们的值是None,并且它们被序列化而没有尾部定界符。

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

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

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

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

在版本 3.1 中更改:默认* dict_type *为collections.OrderedDict

在版本 3.2 中更改:添加了* allow_no_value delimiters comment_prefixes strict empty_lines_in_values default_section interpolation *。

在版本 3.5 中进行了更改:添加了* converters *参数。

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

在版本 3.8 中更改:默认* dict_type *为dict,因为它现在保留插入 Sequences。

  • defaults ( )

    • 返回包含实例范围默认值的字典。
  • sections ( )

    • 返回可用部分的列表; 默认部分未包含在列表中。
  • add_section(* section *)

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

在版本 3.2 中进行了更改:非字符串节名称引发TypeError

  • has_section(* section *)

    • 指示配置中是否存在命名的* section *。 默认部分未被确认。
  • options(* section *)

    • 返回指定* section *中可用选项的列表。
  • has_option(* section option *)

    • 如果给定的* section 存在,并且包含给定的 option ,则返回True;否则返回False。如果指定的 section *为None或为空字符串,则假定为 DEFAULT。
  • read(文件名编码=无)

    • try读取和解析可迭代的文件名,并返回已成功解析的文件名列表。

如果* filenames 是字符串,bytes对象或path-like object,则将其视为单个文件名。如果无法打开以 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 中的新Function:* encoding *参数。以前,所有文件都是使用open()的默认编码读取的。

版本 3.6.1 中的新Function:* filenames *参数接受path-like object

3.7 版中的新Function:* filenames *参数接受bytes对象。

  • read_file(* f source = None *)
    • 从* f *读取和解析配置数据,该数据必须是可迭代的产生 Unicode 字符串(例如,以文本模式打开的文件)。

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

版本 3.2 中的新Function:替换readfp()

  • read_string(* string source =''*)
    • 从字符串中解析配置数据。

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

3.2 版中的新Function。

  • read_dict(* dictionary source =''*)
    • 从任何提供类似 dict items()方法的对象中加载配置。键是部分名称,值是带有应在该部分中显示的键和值的字典。如果使用的字典类型保留 Sequences,则部分及其键将按 Sequences 添加。值会自动转换为字符串。

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

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

3.2 版中的新Function。

  • get((* section option **,* raw = False vars = None * [,* fallback *])
    • 获取名为* section option 值。如果提供了 vars ,则它必须是字典。在 vars (如果提供), section DEFAULTSECT 中按该 Sequences 查找 option 。如果未找到密钥,并且提供了 fallback ,它将用作后备值。 None可以作为 fallback *值提供。

除非* raw *参数为 true,否则所有'%'插值都将在返回值中扩展。以与该选项相同的方式查找插值键的值。

在版本 3.2 中更改:参数* raw vars fallback 仅是关键字,以保护用户避免try将第三个参数用作 fallback *后备(特别是在使用 Map 协议时)。

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

    • 一种便利方法,将指定* section 中的 option *强制为整数。有关 raw vars fallback *的说明,请参见get()
  • getfloat((* section option **,* raw = False vars = None * [,* fallback *])

    • 一种便利方法,将指定* section 中的 option *强制为浮点数。有关 raw vars fallback *的说明,请参见get()
  • getboolean((* section option **,* raw = False vars = None * [,* fallback *])

    • 一种便利方法,用于将指定* section 中的 option *强制为布尔值。请注意,该选项的可接受值为'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。

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

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

  • set(* section option value *)

    • 如果给定的部分存在,则将给定的选项设置为指定的值;否则加NoSectionError。 * option value *必须为字符串;如果不是,则引发TypeError
  • write(* fileobject space_around_delimiters = True *)

    • 将配置的表示形式写入指定的file object,该名称必须以文本模式(接受字符串)打开。此表示形式可以pass将来的read()调用进行解析。如果* space_around_delimiters *为 true,则键和值之间的定界符将被空格包围。
  • remove_option(* section option *)

    • 从指定的* section 中删除指定的 option *。如果该部分不存在,请引发NoSectionError。如果该选项已存在,则返回True;否则返回False
  • remove_section(* section *)

    • 从配置中删除指定的* section *。如果该部分实际上存在,则返回True。否则返回False
  • optionxform(选项)

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

您无需继承解析器的子类即可使用此方法,还可以在实例上将其设置为具有字符串参数并返回字符串的函数。例如,将其设置为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
      • raw 参数为 false 时,get()的递归插值的最大深度。仅当使用默认 interpolation *时,这才有意义。

RawConfigParser Objects

    • 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的旧变体。默认情况下,它已禁用插值Function,并pass其不安全的add_sectionset方法以及传统的defaults=关键字参数处理,允许使用非字符串节名称,选项名称和值。

在版本 3.8 中更改:默认* dict_type *为dict,因为它现在保留插入 Sequences。

Note

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

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

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

  • set(* section option value *)
    • 如果给定的部分存在,则将给定的选项设置为指定的值;否则加NoSectionError。虽然可以将RawConfigParser(或将_raw 参数设置为 true 的ConfigParser)用于内部存储非字符串值,但只能使用字符串值才能实现全部Function(包括内插和输出到文件)。

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

Exceptions

  • exception configparser. Error

  • exception configparser. NoSectionError

    • 未找到指定节时引发异常。
  • exception configparser. DuplicateSectionError

    • 如果在单个 Importing 文件,字符串或字典中多次发现某个段时,如果使用已存在的段名或在严格的解析器中调用add_section(),则会引发异常。

3.2 版中的新增Function:添加了可选的sourcelineno属性以及init()的参数。

  • exception configparser. DuplicateOptionError

    • 如果从单个文件,字符串或字典中读取单个选项两次,则严格解析器会引发异常。这会捕获拼写错误和与大小写敏感有关的错误,例如字典可能有两个键,它们代表同一个不区分大小写的配置键。
  • exception configparser. NoOptionError

    • 在指定的部分中找不到指定的选项时引发异常。
  • exception configparser. InterpolationError

    • 在执行字符串插值时发生问题时引发的异常的 Base Class。
  • exception configparser. InterpolationDepthError

  • exception configparser. InterpolationMissingOptionError

  • exception configparser. InterpolationSyntaxError

    • 当进行替换的源文本不符合要求的语法时,引发异常。 InterpolationError的子类。
  • exception configparser. MissingSectionHeaderError

    • try分析没有节头的文件时引发异常。
  • exception configparser. ParsingError

    • try解析文件时发生错误时引发异常。

在版本 3.2 中进行了更改:为了保持一致,将filename属性和init()参数重命名为source

Footnotes