我正在使用Python configparser生成config.ini
文件来存储我的脚本配置。配置是由代码生成的,但文件的要点是,有一种外部方式可以在以后的阶段更改以编程方式生成的配置。所以文件需要具有良好的可读性,配置选项应该很容易找到。 configparser中的部分是一种很好的方法,可以确保在条目中,条目似乎是随机排序的。例如这段代码:
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
'shuffle': 'True',
'augment': 'True',
# [... some other options ...]
'data_layer_type' : 'hdf5',
'shape_img' : '[1024, 1024, 4]',
'shape_label' : '[1024, 1024, 1]',
'shape_weights' : '[1024, 1024, 1]'
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
使用订单生成config.ini
文件:
[DEFAULT]
shape_weights = [1024, 1024, 1]
# [... some of the other options ...]
shuffle = True
augment = True
data_layer_type = hdf5
# [... some of the other options ...]
shape_img = [1024, 1024, 4]
# [... some of the other options ...]
shape_label = [1024, 1024, 1]
即,条目既不是字母也不是任何其他可识别的顺序。但我想订购,例如形状选项全部在同一个地方,而不是分发给用户浏览...
Here声明无序行为在Python 3.1中已修复,默认情况下使用有序的dicts,但我使用的是Python 3.5.2并获取无序条目。是否需要设置标志或对dict进行排序以便(至少)按字母顺序排序的条目?
有没有办法在使用configparser以编程方式生成config.ini
时定义条目的顺序? (Python 3.5)
这里的问题不是configparser
没有在内部使用OrderedDict
s,而是你正在制作一个无序的文字并分配它。
请注意这是如何排序的:
>>> x = {
... 'shuffle': 'True',
... 'augment': 'True',
... # [... some other options ...]
... 'data_layer_type' : 'hdf5',
... 'shape_img' : '[1024, 1024, 4]',
... 'shape_label' : '[1024, 1024, 1]',
... 'shape_weights' : '[1024, 1024, 1]'
... }
>>> for k in x:
... print(k)
...
shuffle
augment
shape_img
shape_label
shape_weights
data_layer_type
(这作为python3.6中的实现细节变化,作为“小dicts”优化的一部分(所有dicts变得有序) - 由于方便,可能被标准化为python3.7的一部分)
这里的解决方法是确保你一直在分配OrderedDict
s:
config['DEFAULT'] = collections.OrderedDict((
('shuffle', 'True'),
('augment', 'True'),
# [... some other options ...]
('data_layer_type', 'hdf5'),
('shape_img', '[1024, 1024, 4]'),
('shape_label', '[1024, 1024, 1]'),
('shape_weights', '[1024, 1024, 1]'),
))
配置程序似乎默认使用OrderedDicts(因为Python 2.7 / 3.1),这使得ConfigParser(dict_type=OrderedDict)
过时了。但是,默认情况下这不会对条目进行排序,但仍需要手动执行此操作(至少在我的情况下)。
我找到了代码来做here并添加了排序默认值:
import configparser
from collections import OrderedDict
# [...] define your config sections and set values here
#Order the content of DEFAULT section alphabetically
config._defaults = OrderedDict(sorted(config._defaults.items(), key=lambda t: t[0]))
#Order the content of each section alphabetically
for section in config._sections:
config._sections[section] = OrderedDict(sorted(config._sections[section].items(), key=lambda t: t[0]))
# Order all sections alphabetically
config._sections = OrderedDict(sorted(config._sections.items(), key=lambda t: t[0] ))