2.3.5 Sections

Configuration files may be organized in sections with each section containing option/value pairs. The keys argument of the add_option() method can be used to select which section to obtain the option setting from.

For example:

# file: sections.ini
# all devices use the same driver type
driver = ethernet

# path to device #0
path =

# path to device #1
path =

And script:

# file: sections.py
import cfgparse
c = cfgparse.ConfigParser()
c.add_option('driver', dest='driver0', keys='DEV0')
c.add_option('driver', dest='driver1', keys='DEV1')
c.add_option('path', dest='path0', keys='DEV0')
c.add_option('path', dest='path1', keys='DEV1')
opts = c.parse()
print "DEV0:",opts.driver0,opts.path0
print "DEV1:",opts.driver1,opts.path1

Results in:

$ python sections.py
DEV0: ethernet
DEV1: ethernet

The [DEFAULT] section is special. If an option setting cannot be found in a section specified by keys, the option is obtained from the [DEFAULT] section. This section is also utilized if keys is not specified. Note, use of [DEFAULT] is optional. If omitted, option/setting pairs specified before any section declarations are considered part of the [DEFAULT] section. Although not advisable, multiple sections of the same name may exist and are treated as one section without error.