ConfigParserを便利にするクラスを作ったよ。
PythonにはRFC822形式のConfigファイルをパースするConfigParseというモジュールがある。
こいつを便利につかえるラッパークラスを作ってみた。
ソース
import logging,codecs import ConfigParser from ConfigParser import NoOptionError, NoSectionError, ParsingError class config: def __init__(self, conf): # set encoding self.enc='ascii' line = open(files,'r').readline().rstrip() if line.find('=') > 0: self.enc = line.rsplit("=")[-1] self.parser = ConfigParser.SafeConfigParser() try: self.parser.readfp(codecs.open(conf, 'r', self.enc)) except ParsingError: logging.error("ParsingError %s is invalid", CONF) sys.exit(1) def get_opt(self, opt, section="DEFAULT", list=False): try: if( not list): optval = self.parser.get(section,opt) else: optval = self.parser.get(section,opt).split(',') except NoSectionError: logging.warning("NoSectionError: Section Not Found '%s'", section) optval = None except NoOptionError: logging.warning("NoOptionError: Option Not Found '%s'", opt) optval = None return optval CONF="myconf" conf = config(CONF) print conf.get_opt("Encode") print conf.get_opt("Encoding") print conf.get_opt("Image",section="EXT") print conf.get_opt("Image",section="EXTENTION", list=True)
configファイル
#coding=cp932 [DEFAULT] Encode=cp932 PageTitle=にほんご PageIntroduction= [EXTENTION] Image=jpeg,jpg,jpe,gif,png,bmp
実行結果
cp932 WARNING:root:NoOptionError: Option Not Found 'Encoding' None WARNING:root:NoSectionError: Section Not Found 'EXT' None [u'jpeg', u'jpg', u'jpe', u'gif', u'png', u'bmp']
よしよし