Python ConfigParser wrapper

不想你离开。 提交于 2020-01-06 13:12:24

问题


I have a config file and i want to load the options dynamicaly by entering the section and the options name.

For instance this is the config file contents.

[templates]
path = /full/path/to/template

and the config.py file

class Config(object):
    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('config.ini')

        for section in self.config.sections():
            self.__dict__[section] = dict()
            for k, v in self.config.items(section):
                self.__dict__[section][k] = v


    def from_options(self, section, option):
        if section in self.__dict__:
            if option in self.__dict__[section]:
                return self.__dict__[section][option]

if __name__ == '__main__':
    c = Config()
    print c.from_options('templates', 'path')

EDIT: The question is if this a pythonic == right way to do it.


回答1:


config.py

;# if not applicable leave it blank

[templates]
path = /full/path/to/template

configparse.py

class Config(object):
    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('config.py')

    def get_path(self):
        return self.config.get('templates', 'path')

if __name__ == '__main__':
    c = Config()
    print c.get_path()

this should do the trick...



来源:https://stackoverflow.com/questions/7645252/python-configparser-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!