简体   繁体   中英

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.

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 **
[shared]
prop_uniue1 = 1
prop_shared = 10

[unique1]
test_unique = 101

and 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,
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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