python读取ini配置文件
1、导入configparser
import configparser
2、使用
cf = configparser.ConfigParser()
cf.read("app_conf.ini")
3、封装下
class AppConfiguration:
@staticmethod
def get(db_name, config_name):
return cf.get(db_name, config_name)
4、我的代码
#!/usr/bin/env python3
#-- coding: utf-8 --
import configparser
from logger import logger
__author__ = "K.O Wu"
__version__ = "1.0.0"
cf = configparser.ConfigParser()
cf.read("app_conf.ini")
class AppConfiguration:
@staticmethod
def get(db_name, config_name):
try:
return cf.get(db_name, config_name)
except Exception as e:
logger.error("无配置文件或配置文件错误")
logger.error(e)
from config_reader import AppConfiguration
class MSSQL:
def __init__(self):
self.host = AppConfiguration.get('SOURCE_DB', 'db_host')
self.user = AppConfiguration.get('SOURCE_DB', 'db_user')
self.pwd = AppConfiguration.get('SOURCE_DB', 'db_pwd')
self.db = AppConfiguration.get('SOURCE_DB', 'db_name')
self.char = AppConfiguration.get('SOURCE_DB', 'db_char')
[SOURCE_DB]
db_host = 127.0.0.1:1433
db_user = sa
db_pwd = 123456
db_name = EJVMES
db_char = utf8