2011-10-04 5 views
0

설정 파일이 있고 섹션과 옵션 이름을 입력하여 동적으로 옵션을로드하고 싶습니다.파이썬 ConfigParser 래퍼

예를 들어 이것은 구성 파일 내용입니다.

[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') 

편집 : 이것을 파이썬 == 올바른 방법으로 그것을 할 경우 질문입니다.

+1

질문/문제가 무엇입니까? – agf

답변

4

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

이 트릭을 할해야 ...