Db_config.ini [baseconf] host=127.0.0.1 port=3306 user=root password=root db_name= Evaluting_sys [concurrent] processor=20
Python code
1 the corresponding Python code2 ImportSys,os3 ImportConfigparser4 5 classDb_connector:6 def __init__(self, config_file_path):7CF =Configparser.configparser ()8 Cf.read (Config_file_path)9 Tens =cf.sections () One Print 'Section :', S A -o = Cf.options ("baseconf") - Print 'Options:', O the -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") ADb_pwd = Cf.get ("baseconf","Password") at - PrintDb_host, Db_port, Db_user, Db_pwd - -Cf.set ("baseconf","Db_pass","123456") -Cf.write (Open ("Config_file_path","W")) - if __name__=="__main__": inf = Db_connector (".. /conf/db_config.ini")
Universal module: Support Command line +import two forms
Import sys,os,time Import Configparserclassconfig:def __init__ (Self, path): Self.path=Path SELF.CF=Configparser.configparser () Self.cf.read (Self.path) defGet(Self, field, key): Result="" Try: Result= self.cf.Get(field, key) Except:result="" returnresult defSet(self, filed, key, value):Try: self.cf.Set(field, key, value) Cf.write (open (Self.path,'W')) except:returnFalsereturnTrue 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 (1) returnresult 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 (1) returnTrueif__name__ = ="__main__": ifLen (SYS.ARGV) <4: Sys.exit (1) Config_file_path= sys.argv[1] Field= sys.argv[2] Key= sys.argv[3] ifLen (sys.argv) = =4: Print Read_config (Config_file_path, field, key)Else: Value= sys.argv[4] Write_config (config_file_path, field, key, value)
Python read ini configuration file