Multiple configuration files with Python ConfigParser

狂风中的少年 提交于 2020-05-09 19:33:05

问题


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?


回答1:


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




回答2:


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.


来源:https://stackoverflow.com/questions/4029946/multiple-configuration-files-with-python-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!