configparser - Python 配置文件解析模块
configparser 模块提供 ConfigParser
类,能够对类似 windows ini
配置文件的解析。
支持的文件结构
- 配置文件由段落组成,即以 [section] 开头,其后每行为一组键值对,键和值用
=
或:
分隔。 - 默认情况下,段落名
区分
大小写,键名不区分
大小写。 - 可以不提供键值,这种情况下键值对的分隔符也可以省略。
- 值可跨越多行,只要相比第一行有缩进即可。
- 空白行可能被视为多行值的一部分,也可能被忽略,具体取决于解析模式。
- 配置文件可以包含注释,默认以
#
或;
作为前缀。
快速开始
一个基本的配置文件示例:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
生成配置文件
使用以下命令在当前目录下创建包含上述内容的 example.ini
配置文件:
>>> 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)
...
备注:生成的配置项全部为小写字符!
解析配置文件
使用以下命令解析 example.ini
配置文件:
>>> 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'
类型转换
configparser 不会检查配置值的类型,默认将所有配置值都视为字符串。如果需要,可以自行转换配置值的类型:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
configparser 还提供了一系列 getter 方法以便于转换配置值的类型:
>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
提示:该方法对大小写不敏感。类似的,还可以使用
getint()
和getfloat()
方法,也可以自定义类型转换器方法。
ConfigParser 对象
参考官方手册查看所有可用的方法。
提示:在 python 命令行模式下使用
tab
键可以查看所有对象可用的方法或自动补全方法名。
解析 smb.conf
因为 samba 配置文件中有 %
符号用配置变量,与 ConfigPaser
对象的 interpolation
功能相冲突,当解析到某个配置值中包含变量符号时会报错,因此,在初始化解析器对象时应使用 interpolation=None
参数:
>>> config = configparser.ConfigParser(interpolation=None)