简体   繁体   English

使用 Python ConfigParser 的多个配置文件

[英]Multiple configuration files with Python ConfigParser

When calling ConfigParser.read you are allowed to pass a list of strings corresponding to potential locations for configuration files and the function returns a list of those files that were successfully read.调用 ConfigParser.read 时,您可以传递与配置文件的潜在位置相对应的字符串列表,该函数返回成功读取的那些文件的列表。

What is the default behaviour when multiple configuration files are loaded that have overlapping sections/keys?加载具有重叠部分/键的多个配置文件时的默认行为是什么? Do later files in the list override values parsed by earlier ones?列表中较晚的文件是否会覆盖较早文件解析的值? Is the entire section overridden or just conflicting keys?整个部分是否被覆盖或只是冲突的键?

在开始测试之后,ConfigParser 用每个连续的文件覆盖键,读取文件的顺序由传递给 ConfigParser.read 的列表中文件名的顺序决定

Just to give an example for further detail.只是举个例子来了解更多细节。

I can create the following two files: config1.ini我可以创建以下两个文件: config1.ini

# ** config1.ini **
[shared]
prop_uniue1 = 1
prop_shared = 10

[unique1]
test_unique = 101

and config2.ini :config2.ini

# ** config2.ini **
[shared]
prop_uniue2 = 2
prop_shared = 14

[unique2]
test_unique = 102

Then if I run the following I can see how the configs get updated (outputs are shown as comments after the respective print statements):然后,如果我运行以下命令,我可以看到配置如何更新(输出在相应的打印语句后显示为注释):

import ConfigParser

config = ConfigParser.ConfigParser()
config.read(['config1.ini', 'config2.ini'])


print config.sections() # ['shared', 'unique1', 'unique2']
print config.get("shared", "prop_uniue1")  # 1
print config.get("shared", "prop_shared")  # 14
print config.get("unique1", "test_unique") # 101

print config.get("shared", "prop_uniue2")  # 2
print config.get("unique2", "test_unique") # 102

So to summarise it would appear:所以总结一下它会出现:

  • as crasic says the order in which the files are read is determined by the order in which the file names appear in the list given to the read method,正如crasic 所说,读取文件的顺序由文件名出现在给定 read 方法的列表中的顺序决定,
  • the keys are overwritten by later files but this is done at the lower option level rather than the higher section level.这些键会被后面的文件覆盖,但这是在较低的选项级别而不是较高的部分级别完成的。 This means that if you have options that do not occur in later files even if the section does occur then the options from the earlier files will be used.这意味着如果您的选项不会出现在后面的文件中,即使该部分确实出现,那么将使用早期文件中的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM