python configparpser模块的使用
configparser模块的介绍与使用
python的configparser模块提供了对文件后缀为ini
或文件格式与ini文件相同
的配置文件解析功能。
[global]
key1 = value1
key2 = value2
[default]
default1= value1
[...]
......
此类配置文件格式如上,文件内容包含多个部分(sections)如:[global]、[default]等,每个section下分别有多个键值对(配置参数)。通过configparser模块,我们可以很方便的获取文件中的配置参数与section的关联或者自动生成这样的配置文件。
通过pip方式快速安装configparser模块
(venv) [root@master assets_manager]# python -m pip install configparser -i https://pypi.douban.com/simple
Looking in indexes: https://pypi.douban.com/simple
Collecting configparser
Downloading https://pypi.doubanio.com/packages/7a/2a/95ed0501cf5d8709490b1d3a3f9b5cf340da6c433f896bbe9ce08dbe6785/configparser-4.0.2-py2.py3-none-any.whl
Installing collected packages: configparser
Successfully installed configparser-4.0.2
读取配置
下面我们通过代码对smb.conf
配置文件参数进行读取
smb.conf文件
(venv) [root@master assets_manager]# cat ../base_python/book/base_yunwei/smb.conf
# See smb.conf.example for a more detailed config file or
# read the smb.conf manpage.
# Run 'testparm' to verify the config is correct after
# you modified it.
[DEFAULT]
A = 1
[global]
workgroup = SAMBA
security = user
passdb backend = tdbsam
printing = cups
printcap name = cups
load printers = yes
cups options = raw
username map = /etc/samba/smbusers
#[homes]
# comment = Home Directories
# valid users = %S, %D%w%S
# browseable = No
# read only = No
# inherit acls = Yes
#
#[printers]
# comment = All Printers
# path = /var/tmp
# printable = Yes
# create mask = 0600
# browseable = No
#
#[print$]
# comment = Printer Drivers
# path = /var/lib/samba/drivers
# write list = @printadmin root
# force group = @printadmin
# create mask = 0664
# directory mask = 0775
[smb]
path = /data/smb/
browseable = yes
writable = yes
[wlxy]
path = /data/wlxy/
browseable = yes
#[test]
# comment = test
# path = /data/test/
# browseable = yes
python代码
[root@master base_yunwei]# cat conf_parse.py
#!/usr/bin/env python
#coding:utf8
import configparser
config = configparser.ConfigParser() #实例化ConfigParser类
config.read('smb.conf') #读取配置文件
print('获取配置参数:')
#config.sections()以列表形式返回配置文件中所有的配置节,不包括[DEFAULT],[DEFAULT]下的参数会在每一个section中都可以获取到
print(f'配置节:{config.sections()}')
for section in config.sections():
print(f"{section}下的配置参数:")
for key in config[section]: #获取某一section下参数的key值
print(f'参数: {key}, 对应的值: {config[section][key]}') #通过config[section][key]方式可以获取某一section下key对应的值
执行结果:
[root@master base_yunwei]# python conf_parse.py
获取配置参数:
配置节:['global', 'smb', 'wlxy']
global下的配置参数:
参数: workgroup, 对应的值: SAMBA
参数: security, 对应的值: user
参数: passdb backend, 对应的值: tdbsam
参数: printing, 对应的值: cups
参数: printcap name, 对应的值: cups
参数: load printers, 对应的值: yes
参数: cups options, 对应的值: raw
参数: username map, 对应的值: /etc/samba/smbusers
参数: a, 对应的值: 1
smb下的配置参数:
参数: path, 对应的值: /data/smb/
参数: browseable, 对应的值: yes
参数: writable, 对应的值: yes
参数: a, 对应的值: 1
wlxy下的配置参数:
参数: path, 对应的值: /data/wlxy/
参数: browseable, 对应的值: yes
参数: a, 对应的值: 1
生成配置
python代码
[root@master base_yunwei]# cat conf_generate.py
#!/usr/bin/env python
#coding:utf8
import configparser
config = configparser.ConfigParser()
#配置文件参数
config["DEFAULT"] = {
"ListenIP": "0.0.0.0",
"ListenPort": "80"
}
config["mysqld"] = {
"basedir": "/usr/local/mysql",
"datadir": "/data/mysql"
}
config["mysql"] = {}
config["mysql"]["mysqlclient"] = "mysql5.6-client"
config["mysql_safe"] = {}
mysqlsafe = config["mysql_safe"]
mysqlsafe["bin"] = "mysqld_safe"
with open("my.cnf", "w") as configfile:
config.write(configfile) #注意不是configfile.write()
运行结果
[root@master base_yunwei]# python conf_generate.py
[root@master base_yunwei]# cat my.cnf
[DEFAULT]
listenip = 0.0.0.0
listenport = 80
[mysqld]
basedir = /usr/local/mysql
datadir = /data/mysql
[mysql]
mysqlclient = mysql5.6-client
[mysql_safe]
bin = mysqld_safe
configparser下常用的方法及注意点
添加section
n [4]: config.sections()
Out[4]: ['mysqld', 'mysql', 'mysql_safe']
In [5]: config.add_section('define') #添加section
In [6]: config.sections()
Out[6]: ['mysqld', 'mysql', 'mysql_safe', 'define']
删除section
In [14]: for key in config['define']:
...: print(f'{key}')
...:
user
host
listenip
listenport
In [15]: config.remove_option('define', 'user') #删除section:define下key为user的配置参数
Out[15]: True
In [16]: for key in config['define']:
...: print(f'{key}')
...:
host
listenip
listenport
In [17]: config.remove_section('define') #删除section:define
Out[17]: True
In [18]: config.sections()
Out[18]: ['mysqld', 'mysql', 'mysql_safe']
注意点:
- section区分大小写
- section下配置参数的key是不区分大小写的,都会以小写的方式进行保存或展示。
In [22]: config['define']['A'] = '1'
In [23]: config['define']['b'] = '2'
In [24]: for key in config['define']:
...: print(f'{key}')
...:
a
b
- section下配置参数的值是不区分类型的,统一为str类型。可以通过int(),bool(),float()等方法进行转换,也可以通过解析器提供的getint(),getboolean(),getfloat()等方法进行转换。
In [25]: type(config['define']['a'])
Out[25]: str
In [31]: type(config['define'].getint('a'))
Out[31]: int
In [32]: type(int(config['define']['a']))
Out[32]: int
- section为
[DEFAULT]
时,解析器不会显示该section,但是其下的配置参数会被所有的其他section继承,如上述读取配置中的例子。