python解析iniファイルソースコード
iniファイル
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
#!/usr/bin/env python
import ConfigParser;
import string, os, sys;
def main(strConf):
cfg = ConfigParser.ConfigParser();
try:
cfg.read(strConf);
arrSec = cfg.sections();
print(arrSec);
print("echo of section");
for sec in arrSec:
print("section name: %s" %sec);
print("items:");
print(cfg.items(sec));
print("
");
arrKey = cfg.options(sec);
for key in arrKey:
#print("key:%s" %key);
val = cfg.get(sec, key);
print("%s:%s ==> %s" %(sec, key, val));
#end for each key
#end for echo section
except:
print("error cfg!");
if "__main__" == __name__:
#if param ok
nArgLen = len(sys.argv);
print("main args:%d" %nArgLen);
if len(sys.argv) < 2:
print("useage %s %s" %(sys.argv[0], "'cfg file path'"));
exit(0);
#run main function
main(sys.argv[1]);
#cf = ConfigParser.ConfigParser()
#cf.read("test.conf")
# return all section
#s = cf.sections()
#print 'section:', s
#o = cf.options("db")
#print 'options:', o
#v = cf.items("db")
#print 'db:', v
#print '-'*60
#get vlaue
#db_host = cf.get("db", "db_host")
#db_port = cf.getint("db", "db_port")
#db_user = cf.get("db", "db_user")
#db_pass = cf.get("db", "db_pass")
# return an interger value
#threads = cf.getint("concurrent", "thread")
#processors = cf.getint("concurrent", "processor")
#print "db_host:", db_host
#print "db_port:", db_port
#print "db_user:", db_user
#print "db_pass:", db_pass
#print "thread:", threads
#print "processor:", processors
#fix a value and rewrite
#cf.set("db", "db_pass", "zhaowei")
#cf.write(open("test.conf", "w"))
実行:
./parse_conf.py test.ini
main args:2
['concurrent', 'db']
echo of section
section name: concurrent
items:
[('processor', '20'), ('thread', '10')]
concurrent:processor ==> 20
concurrent:thread ==> 10
section name: db
items:
[('db_port', '3306'), ('db_user', 'root'), ('db_host', '127.0.0.1'), ('db_pass', 'password')]
db:db_port ==> 3306
db:db_user ==> root
db:db_host ==> 127.0.0.1
db:db_pass ==> password