2010-08-30 60 views
0

我有一个配置文件(feedbar.cfg),其具有以下内容:的Python ConfigParser持续配置到文件

[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文件)。

谢谢!

回答

3

编辑2:你的代码不工作的原因是因为FeedbarConfig必须从对象继承为一个新风格的类。性能不符合经典的类:

工作,所以解决方案是使用

class FeedbarConfig(object) 

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


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

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

我最后一次尝试使用ConfigParser,我遇到了一些问题:

  1. ConfigParser不处理 多行数值很好。您必须 在后续行上输入空格, 并且一旦解析,则删除空白字符 。因此,无论如何,所有多行 字符串都会转换为一个长字符串 。
  2. ConfigParser降低所有选项 名称。
  3. 无法保证 订单的选项是 写入文件。

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

+0

是的,这是问题所在。 谢谢! – 2010-08-31 07:27:44

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