0

I'm using module configparser in Python 2.7.

In my config file, I want the section log to be optional; my parsing module will provide default values if the section does not exist.

My config file looks like this:

[log]
filename = C:/tmp/myapp.log

Is there a method to read values from a section that may be absent from the config file? Method items reads the values, but assumes the section exists and throws an exception if not.

Leonel
  • 28,541
  • 26
  • 76
  • 103

2 Answers2

1

ConfigParser has method has_section

Bartek Jablonski
  • 2,649
  • 24
  • 32
0

ConfigParser is all about parsing files. As the name suggests. If people start using it for config management they will run into all kinds of weird limitations. You can't have defaults for a section without some wrapping code in ConfigParser. The defaults that ConfigParser mentions are shared across all sections!

I am actively working on a library called configmanager now that solves some of these issues. I believe that one has to declare all the available configs first and provide defaults if possible. configmanager allows to do that. And you can still use configparser for persistence.

To solve your problem with configmanager:

config = Config({
    'log': {
        'filename': 'C:/tmp/myapp.log'
    }
})
config.configparser.load('config.ini')
print(config.log.filename.value)
jbasko
  • 7,028
  • 1
  • 38
  • 51