python configparser的使用

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继承,如上述读取配置中的例子。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
configparser模块是一个用于读取和写入配置文件的Python标准模块。配置文件通常是用于存储应用程序的设置和配置信息的文件。下面是使用configparser模块的基本步骤: 1. 导入configparser模块: ```python import configparser ``` 2. 创建一个ConfigParser对象: ```python config = configparser.ConfigParser() ``` 3. 读取配置文件: ```python config.read('config.ini') ``` 4. 获取配置项的值: ```python value = config.get('section', 'option') ``` 其中,section是配置文件中的一个段落,option是段落中的一个选项。例如,在以下配置文件中: ``` [database] host = localhost port = 3306 user = root password = test123 database = testdb ``` 要获取host的值,可以使用以下代码: ```python host = config.get('database', 'host') print(host) # 输出:localhost ``` 5. 修改配置项的值: ```python config.set('section', 'option', 'new_value') ``` 例如,要将host修改为127.0.0.1,可以使用以下代码: ```python config.set('database', 'host', '127.0.0.1') ``` 6. 写入配置文件: ```python with open('config.ini', 'w') as f: config.write(f) ``` 完整示例: ```python import configparser config = configparser.ConfigParser() # 读取配置文件 config.read('config.ini') # 获取配置项的值 host = config.get('database', 'host') port = config.getint('database', 'port') user = config.get('database', 'user') password = config.get('database', 'password') database = config.get('database', 'database') print('host:', host) print('port:', port) print('user:', user) print('password:', password) print('database:', database) # 修改配置项的值 config.set('database', 'host', '127.0.0.1') # 写入配置文件 with open('config.ini', 'w') as f: config.write(f) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值