What is the intended use of the DEFAULT section in config files used by ConfigParser?

99封情书 提交于 2021-01-20 21:00:24

问题


I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (something that really illustrates the kind of things that are possible).


回答1:


I found an explanation here by googling for "windows ini" "default section". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini:

[host 1]
lh_server=192.168.0.1
vh_hosts = PloneSite1:8080
lh_root = PloneSite1

[host 2]
lh_server=192.168.0.1
vh_hosts = PloneSite2:8080
lh_root = PloneSite2

I can read this using ConfigParser:

>>> cp = ConfigParser.ConfigParser()
>>> cp.read('test1.ini')
['test1.ini']
>>> cp.get('host 1', 'lh_server')
'192.168.0.1'

But I notice that lh_server is the same in both sections; and, indeed, I realise that it will be the same for most hosts I might add. So I can do this, as test2.ini:

[DEFAULT]
lh_server=192.168.0.1

[host 1]
vh_root = PloneSite1
lh_root = PloneSite1

[host 2]
vh_root = PloneSite2
lh_root = PloneSite2

Despite the sections not having lh_server keys, I can still access them:

>>> cp.read('test2.ini')
['test2.ini']
>>> cp.get('host 1', 'lh_server')
'192.168.0.1'

Read the linked page for a further example of using variable substitution in the DEFAULT section to simplify the INI file even more.



来源:https://stackoverflow.com/questions/124692/what-is-the-intended-use-of-the-default-section-in-config-files-used-by-configpa

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