7

我在源代码管理中注意到,使用 ConfigParser 生成的输出文件的内容的顺序永远不会相同。有时,即使没有对值进行任何修改,部分也会更改部分内的位置或选项。

有没有办法在配置文件中保持排序,这样我每次启动应用程序时都不必提交微不足道的更改?

4

4 回答 4

9

看起来这已在Python 3.1和 2.7 中修复,并引入了有序字典:

标准库现在支持在多个模块中使用有序字典。configparser 模块默认使用它们。这允许配置文件被读取、修改,然后以它们的原始顺序写回。

于 2009-07-15T22:45:03.197 回答
3

如果您想比 Alexander Ljungberg 的回答更进一步,并对部分和部分内容进行排序,您可以使用以下内容:

config = ConfigParser.ConfigParser({}, collections.OrderedDict)
config.read('testfile.ini')
# Order the content of each section alphabetically
for section in config._sections:
    config._sections[section] = collections.OrderedDict(sorted(config._sections[section].items(), key=lambda t: t[0]))

# Order all sections alphabetically
config._sections = collections.OrderedDict(sorted(config._sections.items(), key=lambda t: t[0] ))

# Write ini file to standard output
config.write(sys.stdout)

这使用 OrderdDict 字典(以保持排序)并通过覆盖内部 _sections 字典对从外部 ConfigParser 读取的 ini 文件进行排序。

于 2016-12-20T13:11:42.223 回答
2

不,ConfigParser 库以字典哈希顺序写出内容。(如果您查看源代码,您可以看到这一点。)这个模块的替代品做得更好。

我会看看能不能找到一个并添加到这里。

http://www.voidspace.org.uk/python/configobj.html#introduction是我想到的。它不是直接替代品,但非常易于使用。

于 2009-07-15T21:09:51.330 回答
-1

ConfigParser 基于 ini 文件格式,在其设计中应该对顺序不敏感。如果您的配置文件格式对顺序敏感,则不能使用 ConfigParser。如果您有一个对语句顺序敏感的 ini 类型格式,它也可能会使人们感到困惑......

于 2009-07-15T21:55:54.763 回答