Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ConfigParser: how to work out options set in a specific section (rather than defaults)

I have a config file that I read using the RawConfigParser in the standard ConfigParser library. My config file has a [DEFAULT] section followed by a [specific] section. When I loop through the options in the [specific] section, it includes the ones under [DEFAULT], which is what is meant to happen.

However, for reporting I wanted to know whether the option had been set in the [specific] section or in [DEFAULT]. Is there any way of doing that with the interface of RawConfigParser, or do I have no option but to parse the file manually? (I have looked for a bit and I'm starting to fear the worst ...)

For example

[DEFAULT]

name = a

surname = b

[SECTION]

name = b

age = 23

How do you know, using RawConfigParser interface, whether options name & surname are loaded from section [DEFAULT] or section [SECTION]?

(I know that [DEFAULT] is meant to apply to all, but you may want to report things like this internally in order to work your way through complex config files)

thanks!

like image 214
user265454 Avatar asked Dec 11 '25 06:12

user265454


1 Answers

I did this recently by making the options into dictionaries, and then merging the dictionaries. The neat thing about it is that the user parameters override the defaults, and it's easy to pass them all to a function.

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')

defaultparam = {k:v for k,v in config.items('DEFAULT')}
userparam = {k:v for k,v in config.items('Section 1')}

mergedparam = dict(defaultparam.items() + userparam.items())
like image 87
Synco Avatar answered Dec 12 '25 18:12

Synco