Python ConfigParser 将配置保存到文件

发布于 2024-09-16 23:25:38 字数 1348 浏览 10 评论 0原文

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

谢谢!

I have a configuration file (feedbar.cfg), having the following content:

[last_session]
last_position_x=10
last_position_y=10

After I run the following python script:

#!/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

The output is:

10
5

But the file is not updated. The cfg file contents remain the same.

Any suggestions ?

Is there another way to bind config information from a file into a python class ? Something like JAXB in Java (but not for XML, just .ini files).

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心奴独伤 2024-09-23 23:25:38

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 ?

是的。您可以使用 shelvemarshal,或 pickle 保存 Python 对象(例如列表或字典)。

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

  1. ConfigParser 无法处理
    多行值很好。你必须
    在后续行中添加空格,
    一旦解析,空格就是
    已删除。所以你所有的多线
    字符串被转换为一长串
    无论如何字符串。
  2. ConfigParser 将所有选项小写
    名称。
  3. 没有办法保证
    选项的顺序
    写入文件。

虽然,这些不是您当前面临的问题,并且虽然保存文件可能很容易修复,但您可能需要考虑使用其他模块之一以避免将来出现问题。

Edit2: The reason why your code is not working is because FeedbarConfig must inherit from object to be a new-style class. Properties do not work with classic classes.:

So the solution is to use

class FeedbarConfig(object)

Edit: Does JAXB read XML files and convert them to objects? If so, you may want to look at lxml.objectify. This would give you an easy way to read and save your configuration as XML.


Is there another way to bind config information from a file into a python class ?

Yes. You could use shelve, marshal, or pickle to save Python objects (e.g. a list, or dict).

Last time I tried to use ConfigParser, I ran into some problems:

  1. ConfigParser does not handle
    multi-line values well. You have to
    put whitespace on subsequent lines,
    and once parsed, the whitespace is
    removed. So all your multi-line
    strings get converted into one long
    string anyway.
  2. ConfigParser downcases all option
    names.
  3. There is no way to guarantee the
    order in which the options are
    written to file.

Although, these are not the issue that you currently face, and although saving the file may be easy to fix, you may want to consider using one of the other modules to avoid future problems.

做个ˇ局外人 2024-09-23 23:25:38

[我会把它放在评论中,但目前不允许我发表评论]

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

 #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

[I would put this in a comment, but I'm not permitted to comment at this time]

As an aside, you may want to use decorator-style properties, they make things look better, at least in my opinion:

 #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()

Also, according to python docs, SafeConfigParser is the way to go for new applications:

"New applications should prefer this version if they don’t need to be compatible with older versions of Python." -- http://docs.python.org/library/configparser.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文