简体   繁体   English

在ConfigParser使用的配置文件中,DEFAULT部分的用途是什么?

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

I've used ConfigParser for quite a while for simple configs. 我已经使用ConfigParser很长一段时间来进行简单的配置。 One thing that's bugged me for a long time is the DEFAULT section. 长期困扰我的一件事是DEFAULT部分。 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). 我已经阅读了文档,但我真的希望看到一些巧妙的使用示例以及它如何影响文件中的其他部分(这些内容真正说明了可能的事情)。

I found an explanation here by googling for "windows ini" "default section". 我发现了一个解释这里通过google搜索“窗口INI”,“默认部分”。 Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. 总结:您在[DEFAULT]部分放置的任何内容都会传播到其他每个部分。 Using the example from the linked website, let's say I have a config file called test1.ini: 使用链接网站上的示例,假设我有一个名为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: 我可以使用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; 但我注意到两个部分中的lh_server是相同的; and, indeed, I realise that it will be the same for most hosts I might add. 事实上,我意识到对于我可能添加的大多数主机来说都是一样的。 So I can do this, as test2.ini: 所以我可以这样做,就像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: 尽管部分没有lh_server键,我仍然可以访问它们:

>>> 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. 阅读链接页面以获取在DEFAULT部分中使用变量替换的更多示例,以进一步简化INI文件。

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

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