ConfigParser使用的配置文件中DEFAULT部分的预期用途是什么? [英] What is the intended use of the DEFAULT section in config files used by ConfigParser?

查看:53
本文介绍了ConfigParser使用的配置文件中DEFAULT部分的预期用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于简单的配置,我已经使用ConfigParser相当一段时间了.困扰我很长时间的一件事是DEFAULT部分.我不太确定什么是适当的用途.我已经阅读了文档,但是我真的很想看到一些巧妙的用法示例,以及它如何影响文件中的其他部分(确实说明了可能的事情).

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).

推荐答案

我找到了一个解释此处.摘要:您在[DEFAULT]部分中放置的内容都会传播到其他所有部分.使用来自链接网站的示例,假设我有一个名为test1.ini的配置文件:

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

我可以使用ConfigParser读取它:

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'

但是我注意到lh_server在这两节中是相同的;而且,的确,我意识到对于我可能添加的大多数主机来说都是一样的.所以我可以这样做,就像test2.ini一样:

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

尽管这些部分没有lh_server密钥,但我仍然可以访问它们:

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'

阅读链接的页面,以获取在DEFAULT部分中使用变量替换来进一步简化INI文件的更多示例.

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

这篇关于ConfigParser使用的配置文件中DEFAULT部分的预期用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆