3

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'

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
whoopididoo
  • 411
  • 2
  • 10
  • 19
  • In my case the config file was being read using a relative path and my development environment was executing the script form a different directory so it wasn't finding the config file at all. When I ran it myself it worked fine, but I didn't realise what my IDE was doing at first. – ADJenks Dec 01 '22 at 19:18

4 Answers4

3

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.

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
2

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
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Hi @hiro protagonist Thanks for your answer. The thing is I forgot to change that when I posted this code. I changed the config file so as not to reveal too much. So I have now updated the code above like this 'host=conf.get_setting('mainstuff','name') 'and just to confirm its still giving the same error. Sorry about that. – whoopididoo Jul 26 '15 at 12:28
  • hmmm... works for me. (by the way: `complete_path` is not defined in your original code.) – hiro protagonist Jul 26 '15 at 12:35
  • could you try to `print self.default_section_map(section)`? this should help to debug... – hiro protagonist Jul 26 '15 at 12:39
  • Oh I thought that was it for a minute 'complete_path' which should not be there. I took it out and I get the same error. If it works for you I'm wondering what the heck is it? – whoopididoo Jul 26 '15 at 12:40
  • If I try that I get the following – whoopididoo Jul 26 '15 at 12:44
  • exception on domain! {'domain': None} exception on domain! Traceback (most recent call last): File "./t.py", line 53, in host=conf.get_setting('mainstuff','name') File "./t.py", line 15, in get_setting default_setting = self.default_section_map(section)[my_setting] KeyError: 'name' – whoopididoo Jul 26 '15 at 12:45
  • Yes Thank you very much. That is definitely something I can work with. – whoopididoo Jul 26 '15 at 14:35
0

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.

Subhasish Paul
  • 211
  • 3
  • 7
  • In this case i used `config.read(os.path.dirname(os.path.abspath(__file__))+"/../conf/general.conf")` to refer the complete path and it worked for me. – Angel Angeles May 31 '22 at 11:55
0

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

Kal
  • 1