我有一個配置文件(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文件)。
謝謝!
是的,這是問題所在。 謝謝! – 2010-08-31 07:27:44