Search code examples
python-2.7configparserkeyerror

Python ConfigParser KeyError:


I am following an example to read a config file from the following: https://wiki.python.org/moin/ConfigParserExamples

But I get a KeyError and can't figure out why. It is reading the files and I can even print the sections. I think I am doing something really stupid. Any help greatly appreciated.

Here is the code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ConfigParser
import logging

config_default=ConfigParser.ConfigParser()

class Setting(object):
    
    def get_setting(self, section, my_setting):
        
        default_setting = self.default_section_map(section)[my_setting]

        return default_setting

    def default_section_map(self,section):
        dict_default = {}
                
        config_default.read('setting.cfg')
        sec=config_default.sections()

        options_default = config_default.options(section)
        
        logging.info('options_default: {0}'.format(options_default))
        
        for option in options_default:
            try:
                dict_default[option] = config_default.get(section, option)

                if dict_default[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict_default[option] = None

            return dict_default

        return complete_path

if __name__ == '__main__':

    conf=Setting()
    
    host=conf.get_setting('mainstuff','name')
    #host=conf.setting

    print 'host setting is :' + host

My config file is named setting.cfg and looks like this:

[mainstuff]
name              = test1
domain              = test2

[othersection]
database_ismaster   = no
database_master     = test3
database_default    = test4

[mysql]
port                = 311111
user                = someuser
passwd              = somecrazylongpassword

[api]
port                = 1111

And the Error is this...

exception on domain! Traceback (most recent call last): File "./t.py", line 51, in host=conf.get_setting('mainstuff','name') File "./t.py", line 14, in get_setting default_setting = self.default_section_map(section)[my_setting] KeyError: 'name'


Solution

  • you have no general section. in order to get the hostname you need something like

    [general]
    hostname =  'hostname.net'
    

    in your setting.cfg. now your config file matches the program -- maybe you prefer to adapt your porgram to match the config file? ...this should get you started at least.

    UPDATE:

    as my answer is useless now, here is something you could try to build on (assuming it works for you...)

    import ConfigParser
    
    class Setting(object):
    
        def __init__(self, cfg_path):
            self.cfg = ConfigParser.ConfigParser()
            self.cfg.read(cfg_path)
    
        def get_setting(self, section, my_setting):
            try:        
                ret = self.cfg.get(section, my_setting)
            except ConfigParser.NoOptionError:
                ret = None
            return ret
    
    
    if __name__ == '__main__':
    
        conf=Setting('setting.cfg')
        host = conf.get_setting('mainstuff', 'name')
        print 'host setting is :', host