I want to be able to read in a config file and would like to make sure that all keys exist and have a value.

For example if I have this config where watch-dir has been commented out.

[settings]
#watch-dir = /home/pi/shared/ups
poi-dir = /home/pi/shared/POI History
oor-dir = /home/pi/shared/117 History

I would like the key to still exist and have a default value.

Here is what I wrote to handle that but it feels kind of hackish to me. Is there a proper way of doing this with the config parser?

def GetConfig():
    config = ConfigParser()
    config.read('config.ini')

    cfg_defaults = {'watch-dir' : '/home/pi/shared/ups',
                    'poi-dir' : '/home/pi/shared/POI History',
                    'oor-dir' : '/home/pi/shared/117 History'}

    for x in cfg_defaults:
        if not x in dict(config.items('settings')):
            config.set('settings', x, cfg_defaults[x])

    return config
有帮助吗?

解决方案

ConfigParser takes in a dictionary of defaults as the first argument.

cfg_defaults = {'watch-dir' : '/home/pi/shared/ups',
                'poi-dir' : '/home/pi/shared/POI History',
                'oor-dir' : '/home/pi/shared/117 History'}

config = ConfigParser(cfg_defaults)
config.read('config.ini')

return config
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top