在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析或修改并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,ConfigParser模块解析的配置文件的格式类似ini的配置文件格式,就是文件由多个section构成,每个section下又有多个配置项,下面使用一个具体脚本来说明这个模块的使用方法:
chconfig.py
#!/usr/bin/python # -*- coding:gbk -*- # Author: Droeny.zhao # Version: 2010-04-08
import sys import ConfigParser
def getinfo(COLUMN,ITEM): conf=ConfigParser.ConfigParser() CONFIGNAME = 'game.ini' if os.path.isfile(CONFIGNAME): conf.read(CONFIGNAME) conf.sections() try: return conf.get(COLUMN,ITEM) except ConfigParser.NoOptionError, e: print 'Wanning:',e sys.exit() else: print 'Wanning: "%s" is not exists, you must appoint the absolute path of config file with -p or -c.'%(CONFIGNAME) sys.exit()
def setinfo(COLUMN,ITEM,VALUE): conf=ConfigParser.ConfigParser() CONFIGNAME = 'game.ini' if os.path.isfile(CONFIGNAME): conf.read(CONFIGNAME) conf.sections() try: conf.set(COLUMN,ITEM,VALUE) conf.write(open(CONFIGNAME, 'w')) except ConfigParser.NoOptionError, e: print 'Wanning:',e sys.exit() else: print 'Wanning: "%s" is not exists, you must appoint the absolute path of config file with -p or -c.'%(CONFIGNAME) sys.exit()
if __name__ == '__main__': print getinfo('Account','DBName') setinfo('Account','DBName','GameDB') print getinfo('Account','DBName')
|
game.ini
[Account] username = test01 servername = 192.168.0.1 password = 123456 dbname = AccountDB
[Database] username = test02 servername = 192.168.0.2 password = 123456 dbname = GameDB
|
阅读(1125) | 评论(0) | 转发(0) |