熟悉使用ConfigParser库读写配置文件

Python的配置文件


配置文件

setting.ini文件是一个纯文本
[DataBase1]
username = admin
passwors = root

[DataBase2]
hostname = 127.0.0.1
port = 3306

这是一般配置文件的常见的格式,[]里面叫做Section部分的名称,整个[]以及下面的每一项(每一个key=value,叫做Option)都是一个Section区域

Python读取配置文件

#引入依赖库,Python2.x引入ConfigParser Python3.x引入configparser
try:
    import ConfigParser as cReader
except Exception as reason:
    import configparser as cReader

要实现的功能

# -*- coding:utf-8 -*-
"""
    自定义配置文件读取库
    调用ConfigParser,只实现常用功能,作为学习ConfigParser和自用库
"""

#引入依赖库,Python2.x引入ConfigParser Python3.x引入configparser
import json
try:
    import ConfigParser as cReader
except Exception as reason:
    import configparser as cReader


#定义类和函数
class ConfigChannel:
    """建立配置读取类"""

    def __init__(self, configFile):
        """建立ConfigChannel对象"""
        try:
            self.configFile = configFile
            self.channel = cReader.SafeConfigParser()
            self.channel.read(open(configFile))
        except Exception as reason:
            raise

    def getOption(self, Section, Option):
        """获取某区域的某一项配置"""
        try:
            return self.channel.getfloot(Section, Option)
        except Exception as reason:
            try:
                return self.channel.getint(Section, Option)
            except Exception as reason:
                try:
                    return self.channel.getboolean(Section, Option)
                except Exception as reason:
                    return self.channel.get(Section, Option)

    def hasOption(self, Section, Option):
        """判断是否存在这个Option"""
        try:
            return self.channel.has_option(Section, Option)
        except Exception as reason:
            raise

    def showOptions(self):
        """展示所有Options"""
        try:
            return self.channel.options()
        except Exception as reason:
            raise

    def setOption(self, Section, Option, Value):
        """会写或增加配置某区域某一项配置"""
        try:
            self.channel.set(Section, Option, Value)
            self.channel.write(open(self.configFile, "w"))
        except Exception as reason:
            raise

    def rmvOption(self, Section, Option):
        """删除某一个配置项"""
        try:
            self.channel.remove_option(Section, Option)
            self.channel.write(open(self.configFile, "w"))
        except Exception as reason:
            raise

    def hasSection(self, Section):
        """判断是否存在这个Section"""
        try:
            return self.channel.has_section(Section)
        except Exception as reason:
            raise

    def showOptions(self):
        """展示所有Sections"""
        try:
            return self.channel.sections()
        except Exception as reason:
            raise

    def addSection(self, Section):
        """增加一个配置区域"""
        try:
            self.channel.add_section(Section)
            self.channel.write(open(self.configFile, "w"))
        except Exception as reason:
            raise

    def rmvSection(self, Section):
        """删除一个配置区域"""
        try:
            self.channel.remove_section(Section)
            self.channel.write(open(self.configFile, "w"))
        except Exception as reason:
            raise

    def getConfigFromString(self, string):
        """从字符串读取配置并写入"""
        try:
            _dictionary = json.loads(string)
            return self.getConfigFromDictionary(_dictionary)
        except Exception as reason:
            pass
        try:
            configList = string.split(":")
            if len(configList) != 3 or '' in configList:
                raise Exception
            Section = configList[0]
            Option = configList[1]
            Value = configList[2]
            if self.hasSection(Section):
                self.setOption(Section, Option, Value)
            else:
                self.addSection(Section)
                self.setOption(Section, Option, Value)
        except Exception as reason:
            raise

    def getConfigFromDictionary(self, dictionary):
        """从字典读取配置并写入"""
        if not isinstance(dictionary, dict):
            raise
        try:
            for key in dictionary:
                if not isinstance(dictionary.get(key), dict):
                    continue
                if not self.channel.hasSection(key):
                    self.addSection(key)
                for subkey in dictionary[key]:
                    self.channel.setOption(key, subkey,
                                           dictionary[key][subkey])
        except Exception as reason:
            raise

猜你喜欢

转载自www.cnblogs.com/KevinGeorge/p/9108755.html