代码之家  ›  专栏  ›  技术社区  ›  Andrei Ciobanu

python configparser将配置保留到文件

  •  0
  • Andrei Ciobanu  · 技术社区  · 14 年前

    我有一个配置文件(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 回复  |  直到 14 年前
        1
  •  3
  •   unutbu    14 年前

    edit2:代码不起作用的原因是 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对象(例如列表或dict)。

    上次我尝试使用configparser时,遇到了一些问题:

    1. ConfigParser不处理 多行值很好。你必须 在后面的行中加上空格, 一旦被解析,空白区就是 远离的。所以你所有的多行 字符串转换为一个长字符串 不管怎么说。
    2. ConfigParser Downcases All选项 名字。
    3. 没有办法保证 选项的顺序 写入文件。

    尽管这些不是您当前面临的问题,而且保存文件可能很容易解决,但您可能希望考虑使用其他模块之一来避免将来的问题。

        2
  •  2
  •   babbitt    14 年前

    [我会在评论中对此发表评论,但目前不允许我发表评论]

    顺便提一句,你可能想使用装饰风格的属性,它们使事情看起来更好,至少在我看来:

     #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 docs,safeconfigparser是新应用程序的发展方向:

    “如果新应用程序不需要与旧版本的python兼容,那么它们应该更喜欢这个版本。”-- http://docs.python.org/library/configparser.html