小编典典

使用ConfigParser读取没有节名的文件

python

我正在ConfigParser阅读脚本的运行时配置。

我想拥有不提供部分名称的灵活性(有些脚本很简单;它们不需要“部分”)。ConfigParser将抛出NoSectionError异常,并且不接受该文件。

如何才能使ConfigParser仅仅检索(key, value)没有节名的配置文件的元组?

例如:

key1=val1
key2:val2

我宁愿不写配置文件。


阅读 170

收藏
2020-12-20

共1个答案

小编典典

Alex Martelli提供了一种用于ConfigParser解析.properties文件(显然是无节的配置文件)的解决方案。

例如:

$ cat my.props
first: primo
second: secondo
third: terzo

即将是一种.config格式,除了它缺少开头部分的名称。然后,很容易伪造节标题:

import ConfigParser

class 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)
2020-12-20