Python ConfigParser 持久化配置到文件
我有一个配置文件(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文件)。
谢谢!
2 个回答
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
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、marshal,或者 pickle 来保存 Python 对象(比如一个列表或者字典)。
我上次尝试使用 ConfigParser 时遇到了一些问题:
- ConfigParser 对多行值处理得不好。你必须在后续行加上空格,而且一旦解析后,这些空格会被去掉。所以你所有的多行字符串最终都会变成一长串字符串。
- ConfigParser 会把所有选项名都变成小写。
- 没有办法保证选项写入文件的顺序。
虽然这些问题不是你现在面临的,虽然保存文件可能容易解决,但你可能想考虑使用其他模块,以避免将来的麻烦。