Python读取ini配置文件

时间:2022-04-21 00:04:31
db_config.ini
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=evaluting_sys
[concurrent]
processor=20

python代码

 对应的python代码
import sys,os
import ConfigParser class Db_Connector:
def __init__(self, config_file_path):
cf = ConfigParser.ConfigParser()
cf.read(config_file_path) s = cf.sections()
print 'section:', s o = cf.options("baseconf")
print 'options:', o v = cf.items("baseconf")
print 'db:', v db_host = cf.get("baseconf", "host")
db_port = cf.getint("baseconf", "port")
db_user = cf.get("baseconf", "user")
db_pwd = cf.get("baseconf", "password") print db_host, db_port, db_user, db_pwd cf.set("baseconf", "db_pass", "")
cf.write(open("config_file_path", "w"))
if __name__ == "__main__":
f = Db_Connector("../conf/db_config.ini")

通用模块:支持命令行+import两种形式

import sys,os,time
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, filed, key, value):
try:
self.cf.set(field, key, value)
cf.write(open(self.path,'w'))
except:
return False
return True def read_config(config_file_path, field, key):
cf = ConfigParser.ConfigParser()
try:
cf.read(config_file_path)
result = cf.get(field, key)
except:
sys.exit()
return result def write_config(config_file_path, field, key, value):
cf = ConfigParser.ConfigParser()
try:
cf.read(config_file_path)
cf.set(field, key, value)
cf.write(open(config_file_path,'w'))
except:
sys.exit()
return True if __name__ == "__main__":
if len(sys.argv) < :
sys.exit() config_file_path = sys.argv[]
field = sys.argv[]
key = sys.argv[]
if len(sys.argv) == :
print read_config(config_file_path, field, key)
else:
value = sys.argv[]
write_config(config_file_path, field, key, value)