Configuration files may be organized in sections with each section containing
option/value pairs. The keys argument of the
can be used to select which section to obtain the option setting from.
# file: sections.ini [DEFAULT] # all devices use the same driver type driver = ethernet [DEV0] # path to device #0 path = 192.168.0.0 [DEV1] # path to device #1 path = 192.168.0.1
# 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') c.add_file('sections.ini') opts = c.parse() print "DEV0:",opts.driver0,opts.path0 print "DEV1:",opts.driver1,opts.path1
$ python sections.py DEV0: ethernet 192.168.0.0 DEV1: ethernet 192.168.0.1
[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.