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繼承,如上述讀取配置中的例子。