Python ConfigParser 将配置保存到文件
我有一个配置文件(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Edit2:您的代码不起作用的原因是因为
FeedbarConfig
必须从 object 继承为新式类。属性不适用于经典类。:因此解决方案是使用
编辑:JAXB 是否读取 XML 文件并将其转换为对象?如果是这样,您可能需要查看 lxml.objectify。这将为您提供一种简单的方法来读取配置并将其保存为 XML。
是的。您可以使用 shelve,marshal,或 pickle 保存 Python 对象(例如列表或字典)。
上次我尝试使用 ConfigParser 时,遇到了一些问题:
多行值很好。你必须
在后续行中添加空格,
一旦解析,空格就是
已删除。所以你所有的多线
字符串被转换为一长串
无论如何字符串。
名称。
选项的顺序
写入文件。
虽然,这些不是您当前面临的问题,并且虽然保存文件可能很容易修复,但您可能需要考虑使用其他模块之一以避免将来出现问题。
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
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.
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:
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.
names.
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.
[我会把它放在评论中,但目前不允许我发表评论]
顺便说一句,您可能想使用装饰器风格的属性,它们使事情看起来更好,至少在我看来:
另外,根据在 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:
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