保持 ConfigParser 输出文件排序
我在源代码管理中注意到,使用 ConfigParser 生成的输出文件的内容从来不按相同的顺序排列。 有时,即使没有对值进行任何修改,部分也会更改部分内的位置或选项。
有没有一种方法可以在配置文件中对内容进行排序,以便我不必每次启动应用程序时都进行琐碎的更改?
I've noticed with my source control that the content of the output files generated with ConfigParser is never in the same order. Sometimes sections will change place or options inside sections even without any modifications to the values.
Is there a way to keep things sorted in the configuration file so that I don't have to commit trivial changes every time I launch my application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看起来这个问题已在 Python 3.1 和 2.7 中修复,并引入了ordered字典:
Looks like this was fixed in Python 3.1 and 2.7 with the introduction of ordered dictionaries:
如果您想比 Alexander Ljungberg 的答案更进一步,并对各部分和各部分的内容进行排序,您可以使用以下命令:
这使用 OrderdDict 字典(以保持排序)并通过覆盖从 ConfigParser 外部对读取的 ini 文件进行排序内部 _sections 字典。
If you want to take it a step further than Alexander Ljungberg's answer and also sort the sections and the contents of the sections you can use the following:
This uses OrderdDict dictionaries (to keep ordering) and sorts the read ini file from outside ConfigParser by overwriting the internal _sections dictionary.
不会。ConfigParser 库按照字典哈希顺序写出内容。 (如果您查看源代码,您就可以看到这一点。)该模块的替代品可以做得更好。
我看看是否能找到一个并将其添加到此处。
http://www.voidspace.org.uk/python/configobj.html#简介是我想到的。 它不是直接替代品,但非常易于使用。
No. The ConfigParser library writes things out in dictionary hash order. (You can see this if you look at the source code.) There are replacements for this module that do a better job.
I will see if I can find one and add it here.
http://www.voidspace.org.uk/python/configobj.html#introduction is the one I was thinking of. It's not a drop-in replacement, but it is very easy to use.
ConfigParser基于ini文件格式,其设计应该对顺序不敏感。 如果您的配置文件格式对顺序敏感,则不能使用 ConfigParser。 如果你有一个对语句顺序敏感的 ini 类型格式,它也可能会让人们感到困惑......
ConfigParser is based on the ini file format, who in it's design is supposed to NOT be sensitive to order. If your config file format is sensitive to order, you can't use ConfigParser. It may also confuse people if you have an ini-type format that is sensitive to the order of the statements...