首页 > 其他 > 详细

configparser模块的使用

时间:2020-05-26 20:51:33      阅读:62      评论:0      收藏:0      [点我收藏+]
"""
configparser模块的使用
周万春
"""

"""
在生产环境中,我们使用Python编写一些脚本,一般我们会把一些配置信息通过变量的方式在代码里进行指定.
如果有多个代码使用相同的配置,例如每个脚本可能都需要连接数据库。
一旦数据库IP地址发生变化,我们就需要修改所有的Python脚本。 
有一种更好的更通用的方法就是编写一个配置文件,需要使用配置信息的就可以读取该配置文件。
在Python中有一个标准库模块叫做configparse。
"""

"""
配置文件的三种定义:
section:章节,章节需要注意,有一个特殊的章节大写的DEFAULT,下面所有新增加的章节,都会继承这个,后面章节不写option都会继承这个章节的内容。
option :选项,是每一个章节的定义。
value:选项的值。
配置数值类型:
配置文件中,我们看到的bool型,整数型,在我们操作的时候,都是字符串类型。
"""

"""
# vim python_conn_mysql.cnf
[mysql]
host=10.0.0.11
port=3306
user=zhouwanchun
password=123
charset=utf8mb4
"""

# 导入模块
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‘>
user <class ‘str‘>
password <class ‘str‘>
charset <class ‘str‘>
"""

# options查看selctions下配置的参数key
print(conn_mysql_conf.options(mysql))
"""
[‘host‘, ‘port‘, ‘user‘, ‘password‘, ‘charset‘]
"""

# 打印section下所有的参数配置k,v
print(conn_mysql_conf.items(mysql))
"""
[(‘host‘, ‘10.0.0.11‘), (‘port‘, ‘3306‘), (‘user‘, ‘zhouwanchun‘), (‘password‘, ‘123‘), (‘charset‘, ‘utf8mb4‘)]
"""

# 获取section中对应的参数key的值
print(conn_mysql_conf.get(mysql, host))
print(conn_mysql_conf.get(mysql, port))
print(conn_mysql_conf.get(mysql, user))
print(conn_mysql_conf.get(mysql, password))
print(conn_mysql_conf.get(mysql, charset))
"""
10.0.0.11
3306
zhouwanchun
123
utf8mb4
"""

# 读取某个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
user = zhouwanchun
password = 123
charset = utf8mb4
"""

# 删除某个section下的参数
conn_mysql_conf.remove_option(mysql, charset)
print(conn_mysql_conf.options(mysql))
"""
[‘host‘, ‘port‘, ‘user‘, ‘password‘]
"""

# 增加一个section参数
conn_mysql_conf.set(mysql, version, 5.7.26)
print(conn_mysql_conf.options(mysql))
print(conn_mysql_conf.get(mysql, version))
"""
[‘host‘, ‘port‘, ‘user‘, ‘password‘, ‘version‘]
5.7.26
"""

 

configparser模块的使用

原文:https://www.cnblogs.com/zhouwanchun/p/12967236.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!