开发者

Multiple configuration files with Python ConfigParser

开发者 https://www.devze.com 2023-01-21 08:35 出处:网络
When calling ConfigParser.read you are allowed to pass a list of strings corresponding to po开发者_Python百科tential locations for configuration files and the function returns a list of those files th

When calling ConfigParser.read you are allowed to pass a list of strings corresponding to po开发者_Python百科tential 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?


After getting around to testing it, ConfigParser overwrites the keys with each successive file, the order in which the files are read is determined by the order of the file names in the list passed to 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消