繁体   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