Chinaunix首页 | 论坛 | 博客
  • 博客访问: 297950
  • 博文数量: 240
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2016-08-04 18:14
文章分类

全部博文(240)

文章存档

2017年(8)

2014年(4)

2013年(15)

2012年(4)

2011年(14)

2010年(55)

2009年(140)

我的朋友

分类: Python/Ruby

2010-04-08 22:56:33

    在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析或修改并不复杂,在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


阅读(1091) | 评论(0) | 转发(0) |
0

上一篇:chattr 说明

下一篇:python写的最简单的外挂

给主人留下些什么吧!~~