common/config.py
changeset 2 efee419b7a2d
equal deleted inserted replaced
0:eaae9539e910 2:efee419b7a2d
       
     1 import logging
       
     2 
       
     3 
       
     4 class ConfigParser:
       
     5     def __init__(self):
       
     6         self.args = {}       # config file arguments
       
     7         self.registered_args = {}
       
     8         self.log = logging.getLogger('config') 
       
     9 
       
    10     def add_argument(self, name, type=str, default=None):
       
    11         self.registered_args[name] = {'type':type, 'default':default}
       
    12 
       
    13     def load(self, fname):
       
    14         # parse config file
       
    15         with open(fname) as f:
       
    16             exec(f.read(), self.args)
       
    17         # check contents
       
    18         return self.check()
       
    19 
       
    20     def check(self):
       
    21         ok = True
       
    22         for key in self.args.keys():
       
    23             if key == '__builtins__':
       
    24                 continue
       
    25             if key in self.registered_args:
       
    26                 # arg registered, check type
       
    27                 type = self.registered_args[key]['type']
       
    28                 if not isinstance(self.args[key], type):
       
    29                     ok = False
       
    30                     self.log.error("Bad type of config parameter '%s': is %s but should be %s",
       
    31                         key, type(self.args[key]), type)
       
    32             else:
       
    33                 # arg not registered
       
    34                     ok = False
       
    35                     self.log.error("Unknown config parameter '%s'.", key)
       
    36         return ok
       
    37 
       
    38     def __getattr__(self, name):
       
    39         if name in self.args:
       
    40             return self.args[name]
       
    41         
       
    42         # raise error if not found
       
    43         raise AttributeError()
       
    44