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

前端 未结 1 945
轻奢々
轻奢々 2021-02-11 15:12

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

相关标签:
1条回答
  • 2021-02-11 15:53

    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.

    0 讨论(0)
提交回复
热议问题