简体   繁体   中英

Python ConfigParser

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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