美文网首页
python 封装ConfigParser类

python 封装ConfigParser类

作者: 洛丽塔的云裳 | 来源:发表于2020-04-26 21:58 被阅读0次

经常需要读取configparser,封装一个类进行configparser类

import os
import sys
import ConfigParser
class ConfigUtil(object):
    """ 处理config配置的类 """
    def __init__(self, file=None):
        """
        :param path:
        """
        self.file = file
        self.cf = self.load_init(self.file)

    def load_init(self, file):
        """
        :return: 加载conf
        """
        cf = ConfigParser.ConfigParser()
        cf.read(file)
        return cf

    def get_sections(self):
        """
        :return: 获取文件所有的sections
        """
        sections = self.cf.sections()
        return sections

    def get_options(self, section):
        """
        :param section: 获取某个section所对应的键
        :return:
        """
        options = self.cf.options(section)
        return options

    def get_items(self, sections):
        """
        :param sections: 获取某个section所对应的键值对
        :return:
        """
        items = self.cf.items(sections)
        return items

    def get_value(self, section, key):
        """
        :param sections:
        :param key:
        :return: 获取某个section某个key所对应的value
        """
        value = self.cf.get(section, key)
        return value


if __name__ == "__main__":
    """ 测试函数 """
    pwd = os.getcwd()
    file = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".") + '/paicha.conf'
    myconfig = ConfigUtil(file)
    print myconfig.get_sections()
    print myconfig.get_options('test')
    print myconfig.get_value('test', 'mapfile')

相关文章

网友评论

      本文标题:python 封装ConfigParser类

      本文链接:https://www.haomeiwen.com/subject/pnjswhtx.html