14.2. configparser
—配置文件解析器¶
源代码: Lib/configparser.py
此模块提供了 ConfigParser
类,该类实现了一种基本配置语言,该语言提供了类似于Microsoft Windows INI文件中的结构。您可以使用它来编写可以由终端用户轻松定制的Python程序。
注解
此库会对 not 解释或写入在Windows注册表扩展版本的INI语法中使用的值类型前缀。
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. 支持的数据类型¶
配置解析器不会猜测配置文件中的值的数据类型,总是将它们作为字符串存储在内部。这意味着如果您需要其他数据类型,您应该自行转换:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
由于这个任务很常见,config解析器提供了一系列方便的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]
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文件结构¶
配置文件由段组成,每段由 [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?
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
在上面的示例中,interpolation 设置为
BasicInterpolation()
的ConfigParser
将%(home_dir)s
解析为home_dir
(在这种情况下为/Users
)的值。%(my_dir)s
实际上将解析为/Users/lumberjack
。所有内插均按需完成,因此引用链中使用的键不必在配置文件中以任何特定顺序指定。将
interpolation
设置为None
,解析器将简单地返回%(my_dir)s/Pictures
作为my_pictures
的值,并且%(home_dir)s/lumberjack
作为my_dir
的值。
-
class
configparser.
ExtendedInterpolation
¶ 用于实现更高级语法的插值的替换处理程序,例如在
zc.buildout
中使用。扩展插值使用${section:option}
表示来自外部节的值。插值可以跨越多个级别。为方便起见,如果省略section:
部分,则插值默认为当前部分(可能为特殊部分的默认值)。例如,上面使用基本插值指定的配置,将与扩展插值类似:
[Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures
还可以获取来自其他部分的值:
[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"]
只产生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 的列表,包括DEFAULTSECT的 section_proxy 对)。但是,此方法也可以使用参数调用:parser.items(section, raw, vars)
。后一个调用返回指定section
的 option,value 对的列表,其中所有插值都被展开(除非提供了raw=True
)。
映射协议在现有的遗留API之上实现,以便覆盖原始接口的子类仍然应该具有按预期工作的映射。
14.2.7. 自定义解析器行为¶
有几乎和使用它的应用程序一样多的INI格式变体。 configparser
在很大程度上为最大的可用的INI风格提供支持。默认功能主要由历史背景决定,很可能您想要自定义一些功能。
更改特定配置解析器工作方式的最常见方法是使用 __init__()
选项:
defaults,默认值:
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'
delimiters,默认值:
('=', ':')
分隔符是从段中的值分隔键的子字符串。线上的第一个分隔子字符串被视为分隔符。这意味着值(但不是键)可以包含分隔符。
另见
ConfigParser.write()
的 space_around_delimiters 参数。comment_prefixes,默认值:
('#', ';')
inline_comment_prefixes,默认值:
None
注释前缀是指示配置文件中有效注释的开始的字符串。 comment_prefixes 仅用于其他空行(可选缩进),而 inline_comment_prefixes 可以在每个有效值之后使用(例如,段名称,选项和空行)。默认情况下,禁用行内注释,
'#'
和';'
用作整行注释的前缀。在 3.2 版更改: 在以前版本的
configparser
行为匹配comment_prefixes=('#',';')
和inline_comment_prefixes=(';',)
。请注意,配置解析器不支持转义注释前缀,因此使用 inline_comment_prefixes 可能会阻止用户指定包含用作注释前缀的字符的选项值。当有疑问时,避免设置 inline_comment_prefixes。在任何情况下,在多行值中在行的开始处存储注释前缀字符的唯一方式是内插前缀,例如:
>>> from configparser import ConfigParser, ExtendedInterpolation >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) >>> # the default BasicInterpolation could be used as well >>> parser.read_string(""" ... [DEFAULT] ... hash = # ... ... [hashes] ... shebang = ... ${hash}!/usr/bin/env python ... ${hash} -*- coding: utf-8 -*- ... ... extensions = ... enabled_extension ... another_extension ... #disabled_by_comment ... yet_another_extension ... ... interpolation not necessary = if # is not at line start ... even in multiline values = line #1 ... line #2 ... line #3 ... """) >>> print(parser['hashes']['shebang']) #!/usr/bin/env python # -*- coding: utf-8 -*- >>> print(parser['hashes']['extensions']) enabled_extension another_extension yet_another_extension >>> print(parser['hashes']['interpolation not necessary']) if # is not at line start >>> print(parser['hashes']['even in multiline values']) line #1 line #2 line #3
strict,默认值:
True
当设置为
True
时,解析器将不允许在从单个源(使用read_file()
,read_string()
或read_dict()
)读取时的任何段或选项重复。建议在新的应用程序中使用严格的解析器。在 3.2 版更改: 在以前版本的
configparser
行为匹配strict=False
。empty_lines_in_values,默认值:
True
在配置解析器中,值可以跨越多行,只要它们比包含它们的键缩进。默认情况下,解析器还允许空行成为值的一部分。同时,键可以任意缩进以提高可读性。因此,当配置文件变得大而复杂时,用户很容易丢失对文件结构的跟踪。例如:
[Section] key = multiline value with a gotcha this = is still a part of the multiline value of 'key'
这对于用户来说是特别有问题的,以查看她是否使用比例字体来编辑文件。这就是为什么当你的应用程序不需要空行的值,你应该考虑不允许它们。这将使空行分裂键每次。在上面的例子中,它将产生两个键,
key
和this
。default_section,默认值:
configparser.DEFAULTSECT
(即:"DEFAULT"
)允许其他段或插值目的的特定部分的默认值的约定是该库的强大概念,允许用户创建复杂的声明性配置。此部分通常称为
"DEFAULT"
,但可以自定义为指向任何其他有效的部分名称。一些典型值包括:"general"
或"common"
。提供的名称用于在从任何源读取时识别默认部分,并在将配置写回文件时使用。其当前值可以使用parser_instance.default_section
属性来检索,并且可以在运行时被修改(即,将文件从一种格式转换为另一种格式)。interpolation,默认值:
configparser.BasicInterpolation
插值行为可以通过通过 interpolation 参数提供自定义处理程序来定制。
None
可以用于完全关闭插值,ExtendedInterpolation()
提供了一个更先进的变体,灵感来自zc.buildout
。更多关于这个问题在 专用文档部分。RawConfigParser
的默认值为None
。converters,默认值:未设置
Config解析器提供执行类型转换的选项值getter。默认情况下,实现
getint()
,getfloat()
和getboolean()
。如果其他getter是可取的,用户可以在子类中定义它们或传递一个字典,其中每个键是转换器的名称,每个值是一个可调用的实现所述转换。例如,传递{'decimal': decimal.Decimal}
将在解析器对象和所有段代理上添加getdecimal()
。换句话说,可以同时写入parser_instance.getdecimal('section', 'key', fallback=0)
和parser_instance['section'].getdecimal('key', 0)
。如果转换器需要访问解析器的状态,它可以被实现为配置解析器子类上的一个方法。如果此方法的名称以
get
开头,它将在所有节代理上以字典兼容的形式提供(参见上面的getdecimal()
示例)。
更高级的定制可以通过覆盖这些解析器属性的默认值来实现。默认值在类上定义,因此它们可能被子类或属性赋值重写。
-
configparser.
BOOLEAN_STATES
¶ 默认情况下,当使用
getboolean()
时,配置解析器考虑以下值True
:'1'
,'yes'
,'true'
,'on'
和以下值False
:'0'
,'no'
,'false'
,'off'
。您可以通过指定字符串及其布尔结果的自定义字典来覆盖此。例如:>>> custom = configparser.ConfigParser() >>> custom['section1'] = {'funky': 'nope'} >>> custom['section1'].getboolean('funky') Traceback (most recent call last): ... ValueError: Not a boolean: nope >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} >>> custom['section1'].getboolean('funky') False
其他典型的布尔对包括
accept
/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']
-
configparser.
SECTCRE
¶ 用于解析节头的编译正则表达式。默认值匹配
[section]
到名称"section"
。空格被认为是段名称的一部分,因此[ larch ]
将被读为名称" 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 和 delimiters。
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={})¶ 主配置解析器。当给出 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,delimiters,comment_prefixes,strict,empty_lines_in_values,default_section 和 interpolation。
在 3.5 版更改: 添加了 converters 参数。
-
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
。如果指定的 section 是None
或空字符串,则假定为DEFAULT。
-
read
(filenames, encoding=None)¶ 尝试读取和解析文件名列表,返回已成功解析的文件名列表。如果 filenames 是字符串,则将其视为单个文件名。如果无法打开在 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()
的默认编码读取所有文件。
-
read_file
(f, source=None)¶ 从 f 读取和解析配置数据,它必须是可迭代的,以生成Unicode字符串(例如以文本模式打开的文件)。
可选参数 source 指定要读取的文件的名称。如果没有给出 f,则 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])¶ 获取指定 section 的 option 值。如果提供 vars,它必须是字典。 option 在 vars (如果提供),section 和 DEFAULTSECT 中以该顺序查找。如果未找到密钥并提供 fallback,则将其用作回退值。
None
可以作为 fallback 值提供。所有
'%'
内插都在返回值中扩展,除非 raw 参数为真。以与选项相同的方式查找插补键的值。在 3.2 版更改: 参数 raw,vars 和 fallback 是关键字,仅用于保护用户不要尝试使用第三个参数作为 fallback 回退(尤其是在使用映射协议时)。
-
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.2 版更改: vars 中存在的项目不再显示在结果中。之前的行为将实际解析器选项与为插值提供的变量混合。
-
set
(section, option, value)¶ 如果给定段存在,则将给定选项设置为指定值;否则提高
NoSectionError
。 option 和 value 必须是字符串;如果不是,则提高TypeError
。
-
write
(fileobject, space_around_delimiters=True)¶ 将配置的表示写入指定的 file object,必须在文本模式下打开(接受字符串)。此表示可以由未来的
read()
调用解析。如果 space_around_delimiters 为真,则键和值之间的分隔符由空格包围。
-
remove_option
(section, option)¶ 从指定的 section 中删除指定的 option。如果该部分不存在,则提出
NoSectionError
。如果选项存在被删除,返回True
;否则返回False
。
-
remove_section
(section)¶ 从配置中删除指定的 section。如果该部分事实上存在,返回
True
。否则返回False
。
-
optionxform
(option)¶ 将在输入文件中找到的或由客户机代码传递的选项名称 option 转换为应在内部结构中使用的形式。默认实现返回 option 的小写版本;子类可以覆盖此或客户端代码可以在实例上设置此名称的属性以影响此行为。
您不需要将解析器子类化为使用此方法,也可以将其设置在实例上,设置为接受字符串参数并返回字符串的函数。例如,将其设置为
str
将使选项名称区分大小写:cfgparser = ConfigParser() cfgparser.optionxform = str
注意,当读取配置文件时,在调用
optionxform()
之前,将剥离选项名称周围的空格。
-
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.
MAX_INTERPOLATION_DEPTH
¶ 当 raw 参数为假时,
get()
的递归插值的最大深度。这仅在使用默认 interpolation 时才相关。
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_section
和set
方法。注解
考虑使用
ConfigParser
来检查要在内部存储的值的类型。如果你不想插值,你可以使用ConfigParser(interpolation=None)
。-
add_section
(section)¶ 向实例添加名为 section 的节。如果给定名称的节已经存在,则引发
DuplicateSectionError
。如果传递 默认部分 名称,则引发ValueError
。不检查 section 的类型,这允许用户创建非字符串命名的部分。此行为不受支持,可能会导致内部错误。
-
set
(section, option, value)¶ 如果给定段存在,则将给定选项设置为指定值;否则提高
NoSectionError
。虽然可以使用RawConfigParser
(或者 raw 参数设置为true的ConfigParser
)对于非字符串值的 internal 存储,但只能使用字符串值实现完整功能(包括插值和文件输出)。此方法允许用户在内部为键分配非字符串值。此行为不受支持,并且会在尝试写入文件或使其处于非原始模式时导致错误。 使用映射协议API 不允许这种分配发生。
-
14.2.11. 例外¶
-
exception
configparser.
Error
¶ 所有其他
configparser
异常的基类。
-
exception
configparser.
NoSectionError
¶ 未找到指定节时发生异常。
-
exception
configparser.
DuplicateSectionError
¶ 如果
add_section()
使用已经存在的节的名称或在严格解析器中调用时,如果在单个输入文件,字符串或字典中发现多个节,则会抛出异常。3.2 新版功能: 添加了
__init__()
的可选source
和lineno
属性和参数。
-
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 部分。 |