python simple config library

* Python simple config library code
----------------------------------------------------------------------------------
from ConfigParser import SafeConfigParser

class UserConfigParser:
    def __init__(self):
        self.configParser = SafeConfigParser()
        self.sectionName = ''

    # 컨피그 파일을 가져온다
    def getConfigFile(self, fileName):
        self.configParser.read(fileName)

    # "[String]" 형태의 section(subject)를 가져온다.
    def getSection(self, sectionName):
        self.sectionName = sectionName

    def getBoolField(self, fieldName):
        if self.sectionName == '':
            return None
        elif fieldName == '':
            return None

        rawValue = self.configParser.get(self.sectionName, fieldName)
        value = rawValue.rsplit('#',1)[0].strip()

        if value == 'false' or value == 'False' or value == 'FALSE':
            return False
        elif value == 'true' or value == 'True' or value == 'TRUE':
            return True
        else:
            return False

    def getStringField(self, fieldName):
        if self.sectionName == '':
            return None
        elif fieldName == '':
            return None

        rawValue = self.configParser.get(self.sectionName, fieldName)
        value = rawValue.rsplit('#',1)[0].strip()

        if value[0] == "\'" or value[0] == "\"": # 최초 스트링에 \' \" 값을 제거
            value = value[1:]
        if value[-1] == "\'" or value[-1] == "\"": # 마지막 스트링에 \' \" 값을 제거
            value = value[:-1]

        return value
----------------------------------------------------------------------------------


* CONFIG FILE CONTENT (config.cfg)
----------------------------------------------------------------------------------
[SUBJECT]
NAME = JinheeNoh
CITY = Seoul
----------------------------------------------------------------------------------


* Usage
----------------------------------------------------------------------------------
config = UserConfigParser()

config.getConfigFile('./config.cfg')
config.getSection('SUBJECT')
name = config.getStringField('NAME')
city = config.getStringField('CITY')
----------------------------------------------------------------------------------

댓글 없음:

댓글 쓰기