检查很多 settings.ini 选项?

Check for a lot of settings.ini options?

给定一个包含大量设置的 settings.ini 文件,我正在检查每个设置是否存在:

CONFIG = configparser.ConfigParser()
CONFIG.read("settings.ini")

if CONFIG.has_option("A", "A_Config"):
    A_conf = CONFIG.get("A", "A_Config")
else:
    A_conf = "wrong_A_conf"

if CONFIG.has_option("B", "B_Config"):
    B_conf = CONFIG.get("B", "B_Config")
else:
    B_conf = "wrong_B_conf"

是否有其他方法可以检查 10、20、50 设置选项? 我是否需要为每个设置选项编写此有效性检查?

请指教

了解您的问题后,我想建议这些方法:

考虑到 sample.ini 的内容:

[A]
A_config = 1
[B]
B_config = 2
[C]
C_config = 
[D]
D_config = 
  • 方法一

    import configparser
    config = configparser.ConfigParser()
    config.read('sample.ini')
    
    default_value = 999
    
    for each_section in config.sections():
        for key, value in config[each_section].items():
            if value == "":
                globals()[f"{each_section}_config"] = default_value
            else:
                globals()[f"{each_section}_config"] = value    
    print(A_config)
    print(B_config)
    print(C_config)
    print(D_config)
    

但是,我不推荐这种方法。

(Pylint 显示 Undefined variable 'foo7_config' 但代码有效)

我不采用这种方法的原因是您可能会不小心覆盖命名空间中的某些内容。

  • 'Safer'进近(2号)

首先分配所有变量(A_config, B_config ...),使用默认值。

我知道这是一项繁琐的工作,但您只需完成一次并随时更新列表。

A_config, B_config, ..., N_config = [0 for x in range(N)] # or store them in a list.
  • 方法 3(我的推荐)

将它们存储在字典中,无需手动声明它们。

import configparser
config = configparser.ConfigParser()
config.read('sample.ini')

default_value = 999

new_dict = dict()

for each_section in config.sections():
    for key, value in config[each_section].items():
        if value == "":
            new_dict[f"{each_section}_config"] = default_value
        else:
            new_dict[f"{each_section}_config"] = value

print(new_dict)
# 1
print(new_dict['A_config'])

# 2
print(new_dict['B_config'])

# empty
print(new_dict['C_config'])

# empty
print(new_dict['D_config'])

注意:如果遇到这种情况:

[N]
N_config

你可以通过抓住 configparser.ParsingError 来抓住他们 (try/except) 的情况。此错误是由于缺少分隔符而触发的。

使用了this online compiler中的代码。