http://docs.python.org/2/library/configparser.html
http://www.cnblogs.com/sislcb/archive/2008/11/25/1340587.html
ConfigParser模块
对应配置文件:
[db] db_host = 127.0.0.1 db_port = 3307 db_user = root db_pass = password db_none [concurrent] thread = 10 processor = 20
配置解析代码:
#!/usr/bin/env python2.7 #-*- coding:utf8 -*- import ConfigParser import string import os import sys #支持没有空值 conf_par = ConfigParser.RawConfigParser(allow_no_value=True) #conf_par = ConfigParser.ConfigParser() conf_par.read("test.conf") all_sections = conf_par.sections() try: #所有模块 print all_sections #获取所有options print conf_par.options("db") #获取对应的值 print conf_par.get("db","db_host") #获取int类型 print conf_par.getint("db","db_port") print conf_par.get("db","db_none") #修改值 conf_par.set("db","db_port","3307") conf_par.write(open("test.conf",'w')) except ConfigParser.NoOptionError,e: print e
结果输出:
['db', 'concurrent'] ['db_host', 'db_port', 'db_user', 'db_pass', 'db_none'] 127.0.0.1 3307 None