2010-08-30 80 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