The Configparser module was encapsulated last night and is the value obtained from KeyName. Python encapsulation configparser module get Conf.ini value
I originally wanted to get value by section and KeyName in the Config.ini file, and the first two days did not debug. Today Baidu a bit, someone through the way of the dictionary to my and this idea realized, I put this example modified a bit, the code is as follows, and pass the test, later can be used in the automated test framework:
1 #Coding:utf-82 ImportOS3 ImportConfigparser4 5 classDictionary (dict):6 " "7 add a value to the Config.ini parameter Dict8 " "9 def __getattr__(self, keyname):Ten #returns the default value "not find config KeyName" If the key value does not exist One returnSelf.get (KeyName,"no corresponding keyname were found in the Config.ini") A - classConfig (object): - " " the Configparser Two-time package, get value in dictionary - " " - def __init__(self): - #Set Conf.ini path +Current_dir = Os.path.dirname (__file__) -Top_one_dir =os.path.dirname (Current_dir) +file_name = Top_one_dir +"\\conf\\conf.ini" A #instantiating a Configparser object atSelf.config =Configparser.configparser () - Self.config.read (file_name) - #writes key and value to the dictionary according to section - forSectioninchself.config.sections (): - SetAttr (Self, section, Dictionary ()) - forKeyName, valueinchself.config.items (section): in SetAttr (GetAttr (Self, section), KeyName, value) - to defgetconf (Self, section): + " " - Usage: the conf = Config () * info = conf.getconf ("main"). URL $ " "Panax Notoginseng ifSectioninchself.config.sections (): - Pass the Else: + Print("Config.ini could not find the section") A returnGetAttr (self, section) the + if __name__=="__main__": -conf =Config () $info = conf.getconf ("Main"). URL $ PrintInfo
Operation Result:
Conf.ini file
Python package Configparser module get Conf.ini value (optimized)