Оболочка Python ConfigParser - PullRequest
       9

Оболочка Python ConfigParser

0 голосов
/ 04 октября 2011

У меня есть файл конфигурации, и я хочу динамически загружать параметры, вводя раздел и имя параметров.

Например, это содержимое файла конфигурации.

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

и файл config.py

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: Вопрос в том, является ли это питоническим == правильным способом сделать это.

1 Ответ

4 голосов
/ 04 октября 2011

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()

это должно сработать ...

...