Python ConfigParser: how to configure parameters specified in a specific section (and not by default)

I have a configuration file that I am reading using RawConfigParser in the ConfigParser standard library. My configuration file has a section [DEFAULT], and then a section [specific]. When I go through the options in the [special] section, it includes those in the [DEFAULT] section, which is what should happen.

However, for reports, I wanted to know if the parameter was set in the [specific] section or in [DEFAULT]. Is there a way to do this with the RawConfigParser interface, or do I have no option but to manually parse the file? (I searched a bit, and I'm starting to fear the worst ...)

for example

[INITIAL]

name = a

last name = b

[SECTION]

name = b

age = 23

, RawConfigParser, [ ] []?

( , [ ] , , , )

!

+3
3

:

[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

, , 1 .

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")

:

['age', 'name']
['age', 'surname', 'name']
+2

, , . , , .

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())
+5

RawConfigParser.has_option(section, option) ?

0

Source: https://habr.com/ru/post/1733884/


All Articles