0

我有一个配置文件(feedbar.cfg),内容如下:

[last_session]
last_position_x=10
last_position_y=10

在我运行以下 python 脚本后:

#!/usr/bin/env python

import pygtk
import gtk
import ConfigParser
import os
pygtk.require('2.0')

class FeedbarConfig():
 """ Configuration class for Feedbar.
 Used to persist / read data from feedbar's cfg file """
 def __init__(self, cfg_file_name="feedbar.cfg"):
  self.cfg_file_name = cfg_file_name
  self.cfg_parser = ConfigParser.ConfigParser()
  self.cfg_parser.readfp(open(cfg_file_name))

 def update_file(self):
  with open(cfg_file_name,"wb") as cfg_file:
   self.cfg_parser.write(cfg_file)

 #PROPERTIES 
 def get_last_position_x(self):
  return self.cfg_parser.getint("last_session", "last_position_x")
 def set_last_position_x(self, new_x):
  self.cfg_parser.set("last_session", "last_position_x", new_x)
  self.update_file()

 last_position_x = property(get_last_position_x, set_last_position_x)

if __name__ == "__main__":
 #feedbar = FeedbarWindow()
 #feedbar.main()
 config = FeedbarConfig()
 print config.last_position_x
 config.last_position_x = 5
 print config.last_position_x

输出是:

10
5

但是文件没有更新。cfg 文件内容保持不变。

有什么建议么 ?

是否有另一种方法可以将文件中的配置信息绑定到 python 类中?Java 中的 JAXB 之类的东西(但不适用于 XML,只是 .ini 文件)。

谢谢!

4

2 回答 2

3

Edit2:您的代码不起作用的原因是因为FeedbarConfig必须从 object 继承才能成为新型类。属性不适用于经典类。:

所以解决方案是使用

class FeedbarConfig(object)

编辑:JAXB 是否读取 XML 文件并将它们转换为对象?如果是这样,您可能需要查看lxml.objectify。这将为您提供一种简单的方法来读取配置并将其保存为 XML。


Is there another way to bind config information from a file into a python class ?

是的。您可以使用shelvemarshalpickle来保存 Python 对象(例如列表或字典)。

上次我尝试使用 ConfigParser 时遇到了一些问题:

  1. ConfigParser 不能很好地处理多行值。您必须在后续行上放置空格,并且一旦解析,空格就会被删除。因此,无论如何,您所有的多行字符串都会转换为一个长字符串。
  2. ConfigParser 将所有选项名称小写。
  3. 无法保证选项写入文件的顺序。

尽管这些不是您当前面临的问题,并且虽然保存文件可能很容易修复,但您可能需要考虑使用其他模块之一以避免将来出现问题。

于 2010-08-30T21:26:37.490 回答
2

[我会将此放在评论中,但我目前不允许发表评论]

顺便说一句,您可能想要使用装饰器样式的属性,它们使事情看起来更好,至少在我看来:

 #PROPERTIES

 @property 
 def position_x(self):
  return self.cfg_parser.getint("last_session", "last_position_x")

 @position_x.setter
 def position_x(self, new_x):
  self.cfg_parser.set("last_session", "last_position_x", new_x)
  self.update_file()

此外,根据 python 文档,SafeConfigParser 是新应用程序的方法:

“如果不需要与旧版本的 Python 兼容,新应用程序应该更喜欢这个版本。” -- http://docs.python.org/library/configparser.html

于 2010-08-30T21:50:50.553 回答