[英]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. 例如,如果我有其中watch-dir
已被注释掉的此配置。
[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. ConfigParser将默认字典作为第一个参数。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.