开始学习ConfigParser前,请先创建文件 settings.ini 文件内容如下:
[db]
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = password
[misc]
timeout = 8
thread = 10
#!/usr/bin/env python
import os
import sys
from ConfigParser import ConfigParser
class config(ConfigParser):
def __init__(self, path):
self.conf = ConfigParser()
self.path = path
if not os.path.isfile(self.path):
print "not found %s" % self.path
self.conf.read(self.path)
# TypeError: must be type, not classobj
# super(config, self).__init__()
ConfigParser.__init__(self)
def readconf(self):
sections = self.conf.sections()
for section in sections:
keys = self.conf.options(section)
# print "{section}: {keys}".format(section=section, keys=keys)
# items = conf.items(section)
# print "{section}: {items}".format(section=section, items=items)
for key in keys:
print "{section}\t{key}\t: {value}".format(
section=section,
key=key,
value=self.conf.get(section, key))
def writeconf(self, section, key, value):
if section in self.conf.sections():
self.conf.set(section, key, value)
else:
print "please input a valid section."
def rmoption(self, section, key):
if section in self.conf.sections():
self.conf.remove_option(section, key)
else:
print "please input a valid section."
def main():
if len(sys.argv) != 2:
print "[usage] %s configfile" % sys.argv[0]
sys.exit(1)
conf = config(sys.argv[1])
# conf.writeconf('misc', 'key1', 'value1')
conf.readconf()
if __name__ == '__main__':
main()
ConfigParser.ConfigParser 的所有属性方法 如下:
OPTCRE
OPTCRE_NV
SECTCRE
_KEYCRE
__doc__
__init__
__module__
_boolean_states
_get
_interpolate
_interpolation_replace
_read
add_section
defaults
get
getboolean
getfloat
getint
has_option
has_section
items
options
optionxform
read
readfp
remove_option
remove_section
sections
set
write
RawConfigParser, ConfigParser, SafeConfigParser 均可采用上面的方法进行使用, 具体的区别请参考官方文档. 下面简单做一个属性方法的对比.
gnu@dev:~$ diff -u RawConfigParser.txt ConfigParser.txt
--- RawConfigParser.txt 2014-05-19 05:28:02.209363942 -0400
+++ ConfigParser.txt 2014-05-19 05:28:34.505365285 -0400
@@ -1,11 +1,14 @@
OPTCRE
OPTCRE_NV
SECTCRE
+_KEYCRE
__doc__
__init__
__module__
_boolean_states
_get
+_interpolate
+_interpolation_replace
_read
add_section
defaults
gnu@dev:~$ diff -u ConfigParser.txt SafeConfigParser.txt
--- ConfigParser.txt 2014-05-19 05:28:34.505365285 -0400
+++ SafeConfigParser.txt 2014-05-19 05:29:08.637366676 -0400
@@ -8,7 +8,9 @@
_boolean_states
_get
_interpolate
+_interpolate_some
_interpolation_replace
+_interpvar_re
_read
add_section
defaults