#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# configparser模块的使用
# 在生产环境中,我们使用Python编写一些脚本,一般我们会把一些配置信息通过变量的方式在代码里进行指定.
# 如果有多个代码使用相同的配置,例如每个脚本可能都需要连接数据库。
# 一旦数据库IP地址发生变化,我们就需要修改所有的Python脚本。
# 有一种更好的更通用的方法就是编写一个配置文件,需要使用配置信息的就可以读取该配置文件。
# 在Python中有一个标准库模块叫做configparse。
# 配置文件格式
""""
[SECTION_NAME1]
option1 = value1
option2 = value2
[SECTION_NAME2]
option1 = value1
option2 = value2
"""
# 配置文件中,我们看到的bool型,整数型,在我们操作的时候,都是字符串类型。
# 将下面配置文件编辑保存到某个目录下
"""
[root@mysql-host1 ~]# vim python_conn_mysql.cnf
[mysql]
host = 10.0.0.11
port = 3306
username = zhouwanchun
password = 123
charset = utf8mb4
database = dba_test
"""
# 导入模块
import configparser
# 生成一个configParser对象,所有的操作都是根据这个对象来的
conn_mysql_conf = configparser.ConfigParser()
# 读取配置文件
conn_mysql_conf.read('python_conn_mysql.cnf', encoding='utf-8')
# 返回所有的标签,默认的大写的DEFAULT是不返回的,DEFAULT是默认的基类,类似继承,下面所有的都会继承这个属性
print(conn_mysql_conf.sections())
# ['mysql']
# 判断sections是否再配置文件里
print('mysql' in conn_mysql_conf)
# True
# 使用for循环遍历参数key
for k in conn_mysql_conf['mysql']:
print(k, type(k))
# host <class 'str'>
# port <class 'str'>
# username <class 'str'>
# password <class 'str'>
# charset <class 'str'>
# database <class 'str'>
# options查看selctions下配置的参数key
print(conn_mysql_conf.options('mysql'))
# ['host', 'port', 'username', 'password', 'charset', 'database']
# 打印section下所有的参数配置k,v
print(conn_mysql_conf.items('mysql'))
# [('host', '10.0.0.11'), ('port', '3306'), ('username', 'zhouwanchun'), ('password', '123'), ('charset', 'utf8mb4'), ('database', 'dba_test')]
# 获取section中对应的参数key的值
print(conn_mysql_conf.get('mysql', 'host'))
print(conn_mysql_conf.get('mysql', 'port'))
print(conn_mysql_conf.get('mysql', 'username'))
print(conn_mysql_conf.get('mysql', 'password'))
# 10.0.0.11
# 3306
# zhouwanchun
# 123
# 读取某个section下的所有的参数和值
l1 = conn_mysql_conf.options('mysql')
for k in l1:
print("%s = %s" % (k, conn_mysql_conf.get('mysql', k)))
# host = 10.0.0.11
# port = 3306
# username = zhouwanchun
# password = 123
# charset = utf8mb4
# database = dba_test
# 删除某个section下的参数
conn_mysql_conf.remove_option('mysql', 'charset')
print(conn_mysql_conf.options('mysql'))
# ['host', 'port', 'username', 'password', 'database']
# 增加一个section参数
conn_mysql_conf.set('mysql', 'version', '8.0.30')
print(conn_mysql_conf.options('mysql'))
# ['host', 'port', 'username', 'password', 'database', 'version']
print(conn_mysql_conf.get('mysql', 'version'))
# 8.0.30