您的位置:首页 > 编程语言 > Python开发

Python中利用ConfigParser操作配置文件

2014-09-22 15:58 671 查看
在做自动化测试的过程中,经常要用到ConfigParser模块读取配置文件的内容。这里就聊一聊这方面的问题。首先准备一个配置文件,我们取名叫做monitor.cfg。内容如下:
#monitor.cfg
 
[sys]
 #monitor_type=local or remote, if the value is local, the ip/account/password are not useful
 monitor_type=remote
 ip:192.168.1.2
 account:root
 password:root123
 
[memory]
 command: top | head -5 |grep -i memory
 # interval unit second
 duration: 10
 
[cpu]
 command: sar 1 1 |tail -1
 interval: 10

下面通过一个实例,来说明如何读取这个配置文件中的字段内容。
'''
Created on Sep 23, 2014

@author: liu.chunming

@Filename:Config.py
'''

import ConfigParser
import os

def load_config(config_file_name):
    config=ConfigParser.ConfigParser()
    if os.path.exists(config_file_name):
        config.read(config_file_name)
        return config         
    else:
        raise Exception("Config file may not exists")

if __name__=="__main__":
    config_file="monitor.cfg"
    monitor_cfg=load_config(config_file)

    # return all sections and options
    sections=monitor_cfg.sections()
    for section in sections:
        print "section : %s" %section
        #return options in this section
        option=monitor_cfg.options(section)
        print "This section include these options: %s" %option
        #return key-value in this section
        item=monitor_cfg.items(section)
        print "This section include these items: %s" %item
        print "----------------------------"

    print "return value of specific key"
    monitor_type=monitor_cfg.get("sys","monitor_type")
    monitor_ip=monitor_cfg.get("sys","ip")
    monitor_account=monitor_cfg.get("sys","account")
    monitor_password=monitor_cfg.get("sys","password")
    print "monitor_type in section sys is: %s " %monitor_type
    print "monitor_ip in section sys is: %s " %monitor_ip
    print "monitor_account in section sys is: %s " %monitor_account
    print "monitor_password in section sys is: %s " %monitor_password

    #create a new section and write back into the config file
    monitor_cfg.add_section('a_new_section')
    monitor_cfg.set('a_new_section', 'new_key', 'new_value')
    fp=open(config_file,"w")#必须用‘w’,不能用‘a’
    monitor_cfg.write(fp)
    fp.close()
将monitor.cfg放到Config.py的目录下。执行Config.py,输出结果是:
section : sys
This section include these options: ['monitor_type', 'ip', 'account', 'password']
This section include these items: [('monitor_type', 'remote'), ('ip', '192.168.1.2'), ('account', 'root'), ('password', 'root123')]
----------------------------
section : memory
This section include these options: ['command', 'duration']
This section include these items: [('command', 'top | head -5 |grep -i memory'), ('duration', '10')]
----------------------------
section : cpu
This section include these options: ['command', 'interval']
This section include these items: [('command', 'sar 1 1 |tail -1'), ('interval', '10')]
----------------------------
section : a_new_section2
This section include these options: ['new_key']
This section include these items: [('new_key', 'new_value')]
----------------------------
return value of specific key
monitor_type in section sys is: remote 
monitor_ip in section sys is: 192.168.1.2 
monitor_account in section sys is: root 
monitor_password in section sys is: root123
打开monitor.cfg可以看到,在文件末尾增加了一段:
[a_new_section]
new_key = new_value
ConfigParser模块总结

1.基本的读取配置文件
-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2.基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

3.Python的ConfigParser Module中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。

设定配置文件test2.conf

[portal]
url = http://%(host)s:%(port)s/Portal
host = localhost
port = 8080

使用RawConfigParser:

import ConfigParser

cf = ConfigParser.RawConfigParser()

print "use RawConfigParser() read"
cf.read("test2.conf")
print cf.get("portal", "url")

print "use RawConfigParser() write"
cf.set("portal", "url2", "%(host)s:%(port)s")
print cf.get("portal", "url2")

得到终端输出:
use RawConfigParser() read http://%(host)s:%(port)s/Portal
use RawConfigParser() write
%(host)s:%(port)s

改用ConfigParser:

import ConfigParser

cf = ConfigParser.ConfigParser()

print "use ConfigParser() read"
cf.read("test2.conf")
print cf.get("portal", "url")

print "use ConfigParser() write"
cf.set("portal", "url2", "%(host)s:%(port)s")
print cf.get("portal", "url2")

得到终端输出:
use ConfigParser() read http://localhost:8080/Portal
use ConfigParser() write
localhost:8080

改用SafeConfigParser:

import ConfigParser

cf = ConfigParser.SafeConfigParser()

print "use SafeConfigParser() read"
cf.read("test2.conf")
print cf.get("portal", "url")

print "use SateConfigParser() write"
cf.set("portal", "url2", "%(host)s:%(port)s")
print cf.get("portal", "url2")

得到终端输出(效果同ConfigParser):
use SafeConfigParser() read http://localhost:8080/Portal
use SateConfigParser() write
localhost:8080
http://www.linuxso.com/linuxbiancheng/8987.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: