python讀取配置檔案
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
author:skate
time:2013/12/11
python讀取配置檔案
配置檔案樣例:
[[email protected] 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
——————————————————————————————————————————
具體指令碼內容
[[email protected] 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-----