1、创建config文件填写配置信息 如下图:
[mysql]
user = root
password = 123456
host = 127.0.0.1
port = 3306
db = test
2、导入os,configparser模块并封装读取配置文件方法
import os
import configparser
# 读取配置文件
def getConfig(filename, section, option):
"""
:param filename 文件名称
:param section: 服务
:param option: 配置参数
:return:返回配置信息
"""
# 获取当前目录路径
proDir = os.path.split(os.path.realpath(__file__))[0]
# print(proDir)
# 拼接路径获取完整路径
configPath = os.path.join(proDir, filename)
# print(configPath)
# 创建ConfigParser对象
conf = configparser.ConfigParser()
# 读取文件内容
conf.read(configPath)
config = conf.get(section, option)
return config
3、使用封装的方法读取配置信息
# 获取mysql配置信息
host = getConfig("Config", 'mysql', 'host')
port = getConfig("Config", 'mysql', 'port')
user = getConfig("Config", 'mysql', 'user')
password = getConfig("Config", 'mysql', 'password')
database = getConfig("Config", 'mysql', 'db')
print(host, port, user, password, database)
总结:封装成方法后,后期只需要导入该模块使用方法就行,可以增加不同的配置参数文件放在common包下即可。
更多推荐
python--读取config配置文件
发布评论