经常需要读取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')
网友评论