如何配置Python ConfigParser禁止用户配置文件新增选项或章节?
限制ConfigParser仅允许修改已有配置,禁止新增内容
当使用Python的ConfigParser读取多个配置文件时,默认会合并所有配置,后续文件的重复选项会覆盖前者,但新增的章节和选项也会被自动加载。如果希望用户配置文件只能修改默认配置中已存在的章节和选项,一旦出现新增内容就解析失败(避免用户因拼写错误误新增无效配置),可以通过以下方式实现:
示例配置文件
config1.ini(默认配置)
[shared] prop_uniue1 = 1 prop_shared = 10 [unique1] test_unique = 101
config2.ini(用户配置,含非法新增内容)
[shared] prop_uniue2 = 2 prop_shared = 14 [unique2] test_unique = 102
实现方案
核心思路是先读取默认配置并记录所有合法的章节和选项,再单独读取用户配置进行校验,只有当用户配置的所有章节和选项都在默认配置中存在时,才进行合并。
代码实现
import ConfigParser # 加载默认配置,记录所有允许的章节和选项 default_config = ConfigParser.ConfigParser() default_config.read('config1.ini') allowed_sections = set(default_config.sections()) allowed_options = { section: set(default_config.options(section)) for section in allowed_sections } # 加载用户配置并进行合法性校验 user_config = ConfigParser.ConfigParser() user_config.read('config2.ini') # 检查是否存在新增章节 for section in user_config.sections(): if section not in allowed_sections: raise ValueError(f"用户配置存在非法新增章节: [{section}]") # 检查当前章节下是否存在新增选项 for option in user_config.options(section): if option not in allowed_options[section]: raise ValueError(f"章节[{section}]下存在非法新增选项: {option}") # 校验通过后,合并默认配置与用户配置 final_config = ConfigParser.ConfigParser() final_config.read('config1.ini') final_config.read('config2.ini') # 输出测试结果 print(final_config.sections()) # ['shared', 'unique1'] print(final_config.get("shared", "prop_uniue1")) # 1 print(final_config.get("shared", "prop_shared")) # 14 print(final_config.get("unique1", "test_unique")) # 101
代码说明
- 读取默认配置:先加载默认配置文件,将所有合法章节存入集合
allowed_sections,同时用字典allowed_options记录每个章节对应的合法选项集合。 - 校验用户配置:遍历用户配置的每个章节和选项,若发现不在合法列表中的内容,直接抛出
ValueError终止流程。 - 合并配置:只有当用户配置完全合法时,才按正常逻辑合并默认配置与用户配置,确保最终配置中没有新增内容。
当运行上述代码时,会因config2.ini中的prop_uniue2选项和unique2章节是新增内容而抛出错误,达到限制用户配置范围的目的。
内容的提问来源于stack exchange,提问作者Christopher Duncan
相关产品推荐
相关产品推荐

