【发布时间】:2018-04-08 20:03:49
【问题描述】:
我正在使用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-File 的顺序:
[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 中已修复为默认使用有序字典,但我使用的是 Python 3.5.2 并获得无序条目。是否有我需要设置的标志或对 dict 进行排序以使其(至少)按字母顺序排序的条目的方法?
在使用 configparser 以编程方式生成 config.ini 时,有没有办法定义条目的顺序?(Python 3.5)
【问题讨论】:
-
尝试使用
collections.OrderedDict -
我做了:
from collections import OrderedDict,然后是config = configparser.ConfigParser(dict_type=OrderedDict),但这并没有帮助。输出仍然是无序的(每次运行代码时也不同)。 -
你的问题是你分配的字典。字典文字是无序的(在 cpython3.5 及以下版本中)。你想要
config['DEFAULT'] = collections.OrderedDict(<<<iterable of tuples>>>) -
是的,这是有道理的——所以问题是我在执行
config['DEFAULT'] = { ... }时实际上是在将“无序”字典分配给有序字典。你想把它变成我可以接受的答案吗?
标签: python python-3.x config configparser