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!
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())
Given this configuration file:
[DEFAULT]
name = a
surname = b
[Section 1]
name = section 1 name
age = 23
#we should get a surname value from defaults
[Section 2]
name = section 2 name
surname = section 2 surname
age = 24
Here's a program that can understand that Section 1 is using the default surname property.
import ConfigParser
parser = ConfigParser.RawConfigParser()
parser.read("config.ini")
#Do your normal config processing here
#When it comes time to audit default vs. explicit,
#clear the defaults
parser._defaults = {}
#Now you will see which options were explicitly defined
print parser.options("Section 1")
print parser.options("Section 2")
And here's the output:
['age', 'name']
['age', 'surname', 'name']
Doesn't RawConfigParser.has_option(section, option)
do the job?
精彩评论