whoopididoo
whoopididoo

Reputation: 431

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'

Upvotes: 3

Views: 40426

Answers (4)

Kal
Kal

Reputation: 1

The issue in my case was that the config file name is case sensitive. setting.CFG instead of setting.cfg

Upvotes: 0

Marlon Aucallanchi
Marlon Aucallanchi

Reputation: 31

Be sure that your complete file path is setting.cfg. If you put your file in another folder or if it is named different, Python is going to report the same KeyError.

Upvotes: 3

Subhasish Paul
Subhasish Paul

Reputation: 231

This error occurs mainly due to 2 reasons:

  1. Issue in reading the config file due to not getting the proper path. Absolute path may be used. Try reading the config file first whether any issue.

    f = open("config.ini", "r")

    print(f.read())

  2. Not been able to find mentioned section in config file.

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46849

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

Upvotes: 2

Related Questions