ConfigParser enhancements to edit existing configs, part 2

This commit is contained in:
Eric S. Raymond 2000-07-14 14:28:22 +00:00
parent 23adc9f37b
commit 649685ad9b
1 changed files with 41 additions and 5 deletions

View File

@ -36,6 +36,9 @@ ConfigParser -- responsible for for parsing a list of
has_section(section)
return whether the given section exists
has_option(section, option)
return whether the given option exists in the given section
options(section)
return list of configuration options for the named section
@ -68,6 +71,18 @@ ConfigParser -- responsible for for parsing a list of
getboolean(section, options)
like get(), but convert value to a boolean (currently defined as 0 or
1, only)
remove_section(section)
remove the given file section and all its options
remove_option(section, option)
remove the given option from the given section
set(section, option, value)
set the given option
write(fp)
write the configuration state in .ini format
"""
import sys
@ -310,18 +325,40 @@ class ConfigParser:
"""Write an .ini-format representation of the configuration state."""
if self.__defaults:
fp.write("[DEFAULT]\n")
for key in self.__defaults.keys():
fp.write(key + " = " + self.__defaults[key] + "\n")
for (key, value) in self.__defaults.items():
fp.write("%s = %s\n" % (key, value))
fp.write("\n")
for section in self.sections():
fp.write("[" + section + "]\n")
sectdict = self.__sections[section]
for key in sectdict.keys():
for (key, value) in sectdict.items():
if key == "__name__":
continue
fp.write(key + " = " + str(sectdict[key]) + "\n")
fp.write("%s = %s\n" % (key, value))
fp.write("\n")
def remove_option(section, option):
"""Remove an option."""
if not section or section == "DEFAULT":
sectdict = self.__defaults
else:
try:
sectdict = self.__sections[section]
except KeyError:
raise NoSectionError(section)
existed = sectdict.has_key(key)
if existed:
del sectdict[key]
return existed
def remove_section(section):
"""Remove a file section."""
if self.__sections.has_key(section):
del self.__sections[section]
return 1
else:
return 0
#
# Regular expressions for parsing section headers and options. Note a
# slight semantic change from the previous version, because of the use
@ -393,7 +430,6 @@ class ConfigParser:
mo = self.OPTCRE.match(line)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
optname = string.lower(optname)
if vi in ('=', ':') and ';' in optval:
# ';' is a comment delimiter only if it follows
# a spacing character