python - 使用 configparser 写入文件时定义 config.ini 条目的顺序?

标签 python python-3.x config configparser

我正在使用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 中已修复,默认使用有序字典,但我正在使用 Python 3.5.2 并获取无序条目。是否需要设置一个标志或一种对字典进行排序的方法,以便(至少)产生按字母顺序排序的条目?

使用 configparser 以编程方式生成 config.ini 时,是否可以定义条目的顺序? (Python 3.5)

最佳答案

这里的问题不是 configparser 没有在内部使用 OrderedDict ,而是您正在创建一个无序文字并对其进行分配。

注意这是如何不排序的:

>>> 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 中的实现细节进行了更改,作为“小字典”优化的一部分(所有字典都变得有序)——由于方便,可能会标准化为 python3.7 的一部分)

此处的解决方法是确保您始终分配 OrderedDict:

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]'), 
))

关于python - 使用 configparser 写入文件时定义 config.ini 条目的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49722215/

相关文章:

python - 如何使用 python 为我的网站创建短信网关

python - 在numpy矩阵中查找具有不同列索引的行式最大值列

python - 无法使用 pyparsing 正确解析此文件

python - 在 Sphinx 文档中包含源代码

python , Pandas : GroupBy attributes documentation

python - Numpy:需要帮助理解 "in"运算符发生了什么

python - 无法修复 "zipimport.ZipImportError: can' t 解压数据; zlib 不可用”当我输入 "python3.6 get-pip.py"

python - 问题的扩展 "Python logging multiple files using the same logger"

java - 通过 JVM 参数设置 log4j 属性文件 - 为什么顺序很重要?

firebase - 如何通过 cli 输出 Firestore 配置