4

我想将 INI 文件映射为 python 对象。所以如果文件有:

[UserOptions]
SampleFile = sample.txt
SamplePort = 80
SampleInt = 1
Sample = Aja
SampleDate = 10/02/2008

然后我想要:

c = Configuration('sample.ini')

c.UserOptions.SamplePort = 90

我正在寻找setattr但我得到一个递归错误。

这就是我所拥有的:

class Configuration:
    def __init__ (self, fileName):
        cp = SafeConfigParser()
        cp.read(fileName)
        self.__parser = cp
        self.fileName = fileName

    def __getattr__ (self, name):
        if name in self.__parser.sections():
            return Section(name, self.__parser)
        else:
            return None

    def __str__ (self):
        p = self.__parser
        result = []
        result.append('<Configuration from %s>' % self.fileName)
        for s in p.sections():
            result.append('[%s]' % s)
            for o in p.options(s):
                result.append('%s=%s' % (o, p.get(s, o)))
        return '\n'.join(result)

class Section:
    def __init__ (self, name, parser):
        self.__name = name
        self.__parser = parser

    def __getattr__ (self, name):
        if self.__dict__.has_key(name):       # any normal attributes are handled normally
            return __getattr__(self, item)
        else:
            return self.__parser.get(self.name, name)

    def __setattr__(self, item, value):
        """Maps attributes to values.
        Only if we are initialised
        """
        if self.__dict__.has_key(item):       # any normal attributes are handled normally
            dict.__setattr__(self, item, value)
        else:
            self.__parser.set('UserOptions',item, value)

现在我想知道为什么self.__parser.set('UserOptions',item, value)会出现错误。我阅读了 pythons 文档,但我不知道该怎么做。我怀疑我需要存储一个带有字段名称的字典并首先查看那里但是如何?

4

2 回答 2

4

您正在尝试按要求获取这些部分。但是迭代部分和选项并将它们作为属性添加到__init__. 我编辑了我的示例以支持 setattr 。你的问题在这里解释你正在分配属性,__setattr__而你应该__dict__使用

from ConfigParser import  SafeConfigParser

class Section:
    def __init__(self, name, parser):
        self.__dict__['name'] = name
        self.__dict__['parser'] = parser

    def __setattr__(self, attr, value):
        self.__dict__[attr] = str(value)
        self.parser.set(self.name, attr, str(value))

class Configuration(object):
    def __init__(self, fileName):
        self.__parser = SafeConfigParser()
        self.__parser.read(fileName)
        self.fileName = fileName
        for section in self.__parser.sections():
            setattr(self, section, Section(section, self.__parser))
            for option in self.__parser.options(section):
                setattr(getattr(self, section), option,
                        self.__parser.get(section, option))

    def __getattr__(self, attr):
        self.__parser.add_section(attr)
        setattr(self, attr, Section(attr, self.__parser))
        return getattr(self, attr)

    def save(self):
        f = open(self.fileName, 'w')
        self.__parser.write(f)
        f.close()

c = Configuration('config.ini')

print dir(c) -> will print all sections
print dir(c.UserOptions) -> will print all user options
print c.UserOptions.sampledate

c.new.value = 10
c.save()
于 2009-05-13T23:04:38.153 回答
4

你的问题在Section.__init__. 当你设置self.__name = name它调用你的__setattr__方法时,没有找到关键__dict__所以它去

 self.__parser.set('UserOptions',item, value)

所以现在它需要self.__parser.

哪个还没有设置。所以它试图让它使用__getattr__. 它发送它寻找self.__parser。哪个还没有设置。所以它试图让它使用__getattr__. 所以......你明白了:-)

避免这种情况的一种方法是Section.__setattr__像这样添加条件

if item.startswith('_') or self.__dict__.has_key(item):
   ^^^^^^^^^^^^^^^^^^^^^^^
   ...

这将确保__name__parser在初始化时正确设置。

于 2009-05-13T23:11:08.940 回答