author:skate
time:2013/12/11
python读取配置文件
配置文件样例:
[root@slave92 python]# more config.ini
[sec1]
user = root
[concurrent]
processor = 20
[baseconf]
user2 = user2
user1 = root1
host = 127.0.0.1
db_name = skatebd
user = rootroot
password = root
port = 3306
——————————————————————————————————————————
具体脚本内容
[root@slave92 python]# vi opcfg.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
#author: skate
#time:2013/12/10
#funcation: use to read config
#version: 0.1
#---------------------
#time modificator desc
#2013/12/11 skate support class and param for cmd
#
#---------------------
import sys,os,time,getopt
import ConfigParser
class Config:
def __init__(self, path):
self.path = path
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.path)
def get(self, field, key):
result = ""
try:
result = self.cf.
get(field, key)
except:
result = ""
return result
def set(self,section, field, key, value):
try:
if len(section) > 0:
self.cf.add_section(section)
if len(field) >0 and len(value) > 0:
self.cf.set(field, key, value)
self.cf.write(open(self.path,'w'))
except:
return Flase
return True
def remove_option(self, field,key):
try:
if len(key) >0 and len(field) > 0:
self.cf.remove_option(field,key)
self.cf.write(open(self.path,'w'))
except:
return Flase
return True
def remove_section(self,field):
try:
if len(field) >0:
self.cf.remove_section(field)
self.cf.write(open(self.path,'w'))
except:
return Flase
return True
def read_config(config_file_path, field, key):
try:
config = Config(config_file_path)
result = config.get(field,key)
except:
sys.exit(1)
return result
def write_config(config_file_path,section, field, key, value):
try:
config = Config(config_file_path)
return Flase
#sys.exit(1)
return True
def remove_option_config(config_file_path, field,key):
try:
config = Config(config_file_path)
config.remove_option(field,key)
except:
return Flase
return True
def remove_section_config(config_file_path,field):
try:
config = Config(config_file_path)
config.remove_section(field)
except:
return Flase
return True
def usage():
'''opcfg.py OPTIONS:.
configfile c The configuration file name
field F The name of field
addkey a The adding the name key
getkey g The getting the name key
value v The value of key
add_section A The adding the name of section
delkey d The deleteing the name of key
del_scetion D The deleteting the name of section
help h Get the help file
eg:
get key: # opcfg.py -c config.ini -F section -g user
add key: # opcfg.py -c config.ini -F section -a user -v root
add section # opcfg.py -c config.ini -A sec1 -F sec1 -a sec1_user -v root
del key # opcfg.py -c config.ini -F section -d sec1
del section # opcfg.py -c config.ini -D sec1 '''
if __name__ == "__main__":
try:
if len(sys.argv) < 2:
sys.exit(1)
opts,args = getopt.getopt(sys.argv[1:],"hc:F:a:g:v:A:d:D:",["help","configfile=","field=","addkey=","getkey=","value=","add_section=","delkey=","del_section="])
config_file_path = ""
field = ""
addkey = ""
getkey = ""
keyvalue = ""
add_section = ""
delkey = ""
del_section = ""
for op, value in opts:
if op in ( "-h","--help"):
print(usage.__doc__)
elif op in ("-c","--configfile"):
config_file_path = value
elif op in ("-s","--section"):
init_section = value
elif op in ("-F","--field"):
field = value
elif op in ("-a","--addkey"):
addkey = value
elif op in ("-g","--getkey"):
getkey = value
elif op in ("-v","--value"):
keyvalue = value
elif op in ("-A","--add_section"):
add_section = value
elif op in ("-d","--delkey"):
delkey = value
elif op in ("-D","--del_section"):
del_section = value
#print "config_file_path: %s" % config_file_path
#print "field: %s" % field
#print "addkey: %s" % addkey
#print "getkey: %s" % getkey
#print "keyvalue: %s" % keyvalue
#print "add_section: %s" % add_section
#print "del_section: %s" % del_section
if len(getkey) > 0:
print read_config(config_file_path, field, getkey)
elif len(addkey) > 0 or len(add_section) > 0:
write_result = write_config(config_file_path,add_section,field, addkey, keyvalue)
print "write_result :%s" % write_result
if write_result == True:
print "write config success!!"
else:
print "write config error!!"
elif len(delkey) >0 and len(field) >0:
remove_option_config(config_file_path, field,delkey)
elif len(del_section) > 0 :
remove_section_config(config_file_path,del_section)
elif len(delkey) >0 and len(field) > 0 :
remove_option_config(config_file_path, field,delkey)
else:
print "param error"
except:
print "configfile have problem"
本程序知识点:
1. python中使用命令行选项
2. python操作配置文件
详解
1. python中使用命令行选项
python如果想处理参数,需要用到sys模块,通过sys模块可以获得参数相关信息,如下:
参数个数:len(sys.argv)
脚本名: sys.argv[0]
参数1: sys.argv[1]
参数2: sys.argv[2]
getopt函数可以处理命令行选项,其语法如下:
getopt.getopt(args, options[, long_options])
本示例中解析
opts,args = getopt.getopt(sys.argv[1:],"hc:F:a:g:v:A:d:D:",["help","configfile=","field=","addkey=","getkey=","value=","add_se
ction=","delkey=","del_section="])
A. sys.argv[1:]为要处理的参数列表,sys.argv[0]为脚本名,所以用sys.argv[1:]过滤掉脚本名。
B. "hc:F:a:g:v:A:d:D:": 当一个选项只表示开关状态时,即后面不带附件参数时,在分析串中只写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":"号;所以”h“是一个开关选项,”c:”,“F:”,“a:”,“g:”,“v:”,“A:”,“d:”,“D:“则表示后面应该带一个参数。
C. 调用getopt函数。函数返回两个列表:opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数。opts是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串''。
getopt函数的第三个参数[, long_options]为可选的长选项参数,上面例子中的都为短选项(如 -c, -F等)
长选项格式举例:
--version
--file=error.txt
让一个脚本同时支持短选项和长选项
getopt.getopt(sys.argv[1:], "Vf:", ["version", "file="])
2. python操作配置文件
常用选项:
config = ConfigParser.ConfigParser() //初始化config实例(建立一个空的数据集实例)
config.read(filename) //通过load文件filename来初始化config实例
config.get(section, key) //获得指定section中的key的value
config.set(section, key, value) //在指定section中,添加一对key-value键值对
config.remove_option(section, key) //删除指定section的key
config.remove_section(section) //删除指定section
config.write(open(filename,'w')) //保存配置
详细参考内容:http://docs.python.org/2/library/configparser.html
------end-----