python:configparser --- 配置文件解析器
此模块提供了它实现一种基本配置语言 ConfigParser 类,这种语言所提供的结构与 Microsoft Windows INI 文件的类似。 你可以使用这种语言来编写能够由最终用户来自定义的 Python 程序。
备注 这个库 并不 能够解析或写入在 Windows Registry 扩展版本 INI 语法中所使用的值-类型前缀。
快速起步
让我们准备一个非常基本的配置文件,它看起来是这样的:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[forge.example]
User = hg
[topsecret.server.example]
Port = 50022
ForwardX11 = no
INI 文件的结构描述见 以下章节。 总的来说,这种文件由多个节组成,每个节包含多个带有值的键。 configparser 类可以读取和写入这种文件。 让我们先通过程序方式来创建上述的配置文件。
>>>
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['forge.example'] = {}
config['forge.example']['User'] = 'hg'
config['topsecret.server.example'] = {}
topsecret = config['topsecret.server.example']
topsecret['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
如你所见,我们可以把配置解析器当作一个字典来处理。 两者确实存在差异,将在后文说明,但是其行为非常接近于字典所具有一般行为。
现在我们已经创建并保存了一个配置文件,让我们再将它读取出来并探究其中包含的数据。
>>>
config = configparser.ConfigParser()
config.sections()
[]
config.read('example.ini')
['example.ini']
config.sections()
['forge.example', 'topsecret.server.example']
'forge.example' in config
True
'python.org' in config
False
config['forge.example']['User']
'hg'
config['DEFAULT']['Compression']
'yes'
topsecret = config['topsecret.server.example']
topsecret['ForwardX11']
'no'
topsecret['Port']
'50022'
for key in config['forge.example']:
print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
config['forge.example']['ForwardX11']
'yes'
正如我们在上面所看到的,相关的 API 相当直观。 唯一有些神奇的地方是 DEFAULT 小节,它为所有其他小节提供了默认值 1。 还要注意小节中的键大小写不敏感并且会存储为小写形式 1。
将多个配置读入单个 ConfigParser 是可能的,其中最近添加的配置具有最高优先级。 任何冲突的键都会从更近的配置获取并且先前存在的键会被保留。
>>>
another_config = configparser.ConfigParser()
another_config.read('example.ini')
['example.ini']
another_config['topsecret.server.example']['Port']
'50022'
another_config.read_string("[topsecret.server.example]\nPort=48484")
another_config['topsecret.server.example']['Port']
'48484'
another_config.read_dict({"topsecret.server.example": {"Port": 21212}})
another_config['topsecret.server.example']['Port']
'21212'
another_config['topsecret.server.example']['ForwardX11']
'no'
此行为等价于一次 ConfigParser.read() 调用并向 filenames 形参传入多个文件。
支持的数据类型
配置解析器并不会猜测配置文件中值的类型,而总是将它们在内部存储为字符串。 这意味着如果你需要其他数据类型,你应当自己来转换:
>>>
int(topsecret['Port'])
50022
float(topsecret['CompressionLevel'])
9.0
由于这种任务十分常用,配置解析器提供了一系列便捷的获取方法来处理整数、浮点数和布尔值。 最后一个类型的处理最为有趣,因为简单地将值传给 bool() 是没有用的,bool(‘False’) 仍然会是 True。 为解决这个问题配置解析器还提供了 getboolean()。 这个方法对大小写不敏感并可识别 ‘yes’/‘no’, ‘on’/‘off’, ‘true’/‘false’ 和 ‘1’/‘0’ 1 等布尔值。 例如:
>>>
topsecret.getboolean('ForwardX11')
False
config['forge.example'].getboolean('ForwardX11')
True
config.getboolean('forge.example', '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'
>>>
topsecret.get('CompressionLevel', '3')
'9'
还需要注意的一点是解析器层级的 get() 方法提供了自定义的更复杂接口,它被维护用于向下兼容。 当使用此方法时,回退值可以通过 fallback 仅限关键字参数来提供:
>>>
config.get('forge.example', '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,在此情况下键/值分隔符也可以被省略。 值还可以跨越多行,只要值的其他行带有比第一行更深的缩进。 依据解析器的具体模式,空白行可能会被视为多行值的组成部分或是被忽略。
在默认情况下,有效的节名称可以是不包含 ‘\n’ 或 ‘]’ 的任意字符串。 要改变此设定,请参阅 ConfigParser.SECTCRE。
配置文件可以包含注释,要带有指定字符前缀 (默认为 # 和 ; 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 = Tru