Alex Martelli提供了一种用于
ConfigParser解析
.properties文件(显然是无节的配置文件)的解决方案。
例如:
$ cat my.propsfirst: primosecond: secondothird: terzo
即将是一种.config格式,除了它缺少开头部分的名称。然后,很容易伪造节标题:
import ConfigParserclass FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[asection]n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline()
用法:
cp = ConfigParser.SafeConfigParser()cp.readfp(FakeSecHead(open('my.props')))print cp.items('asection')输出:
[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]他的解决方案是一个类似文件的包装器,该包装器将自动插入一个虚拟节标题来满足
ConfigParser的要求。
我认为MestreLion的“ read_string”注释很好,很简单,值得举一个例子。
对于Python 3.2+,您可以实现“虚拟部分”的想法,如下所示:
with open(CONFIG_PATH, 'r') as f: config_string = '[dummy_section]n' + f.read()config = configparser.ConfigParser()config.read_string(config_string)



