簡體   English   中英

Python ConfigParser將配置持久保存到文件

[英]Python ConfigParser persist configuration to file

我有一個配置文件(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文件)。

謝謝!

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對象(例如列表或dict)。

上一次我嘗試使用ConfigParser時,遇到了一些問題:

  1. ConfigParser不能很好地處理多行值。 您必須在后面的行上放置空格,並且在解析之后,空格將被刪除。 因此,無論如何,所有多行字符串都將轉換為一個長字符串。
  2. ConfigParser會將所有選項名稱壓縮。
  3. 無法保證將選項寫入文件的順序。

盡管這些不是您當前面臨的問題,並且盡管保存文件可能很容易解決,但是您可能要考慮使用其他模塊之一以避免將來出現問題。

[我會對此發表評論,但目前不允許我發表評論]

順便說一句,您可能要使用裝飾器樣式的屬性,它們使外觀看起來更好,至少在我看來:

 #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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM