The set_option()
method of the object returned from the add_file()
method of the ConfigParser
class can be used to modify an option setting
in a specific configuration file. This method offers more direct control of
which section the option to be set is located in. If the option is not in the
section specified, the option will be added to that section. If multiple copies
of the option exist in the desired section, all copies will be updated. This
method does not return anything.
name, value[, keys][, help]) |
name is a required positional argument and is the name of the option to set the value of.
value is a required positional argument and is the new option value.
keys is an optional keyword argument. This key list identifies the configuration file section where option is located or to be added.
help is an optional string keyword argument. This string is placed ahead of an option setting if it is necessary to add the option to a section.
For example:
[DEFAULT] # this section applies to all devices timeout = 10 # in seconds retries = 3 [DEV0] # this section if for settings specific to device #0 retries = 5 # overrides default
And script:
import cfgparse,sys c = cfgparse.ConfigParser() f = c.add_file('set_option.ini') f.set_option('retries',6) f.set_option('retries',10,keys='DEV0') f.set_option('retries',100,keys='DEV1',help='In new section') f.write(sys.stdout)
Results in:
$ python set_option.py [DEFAULT] # this section applies to all devices timeout = 10 # in seconds retries = 6 [DEV0] # this section if for settings specific to device #0 retries = 10 # overrides default [DEV1] # In new section retries = 100