Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-10 08:39:17

0001 #!/usr/bin/env python
0002 # Licensed under the Apache License, Version 2.0 (the "License");
0003 # you may not use this file except in compliance with the License.
0004 # You may obtain a copy of the License at
0005 # http://www.apache.org/licenses/LICENSE-2.0
0006 #
0007 # Authors:
0008 # - Paul Nilsson, paul.nilsson@cern.ch, 2019
0009 
0010 import os
0011 import re
0012 
0013 try:
0014     import ConfigParser
0015 except Exception:  # Python 3
0016     import configparser as ConfigParser  # noqa: N812
0017 
0018 _default_path = os.path.join(os.path.dirname(__file__), 'default.cfg')
0019 _path = os.environ.get('HARVESTER_PILOT_CONFIG', _default_path)
0020 _default_cfg = _path if os.path.exists(_path) else _default_path
0021 
0022 
0023 class _ConfigurationSection(object):
0024     """
0025     Keep the settings for a section of the configuration file
0026     """
0027 
0028     def __getitem__(self, item):
0029         return getattr(self, item)
0030 
0031     def __repr__(self):
0032         return str(tuple(list(self.__dict__.keys())))  # Python 2/3
0033 
0034     def __getattr__(self, attr):
0035         if attr in self.__dict__:
0036             return self.__dict__[attr]
0037         else:
0038             raise AttributeError('Setting \"%s\" does not exist in the section; __dict__=%s' % (attr, self.__dict__))
0039 
0040 
0041 def read(config_file):
0042     """
0043     Read the settings from file and return a dot notation object
0044     """
0045 
0046     config = ConfigParser.ConfigParser()
0047     config.read(config_file)
0048 
0049     obj = _ConfigurationSection()
0050 
0051     for section in config.sections():
0052 
0053         settings = _ConfigurationSection()
0054         for key, value in config.items(section):
0055             # handle environmental variables
0056             if value.startswith('$'):
0057                 tmpmatch = re.search(r'\$\{*([^\}]+)\}*', value)  # Python 3 (added r)
0058                 envname = tmpmatch.group(1)
0059                 if envname not in os.environ:
0060                     raise KeyError('{0} in the cfg is an undefined environment variable.'.format(envname))
0061                 value = os.environ.get(envname)
0062             # convert to proper types
0063             if value == 'True' or value == 'true':
0064                 value = True
0065             elif value == 'False' or value == 'false':
0066                 value = False
0067             elif value == 'None' or value == 'none':
0068                 value = None
0069             elif re.match(r'^\d+$', value):  # Python 3 (added r)
0070                 value = int(value)
0071             setattr(settings, key, value)
0072 
0073         setattr(obj, section, settings)
0074 
0075     return obj
0076 
0077 
0078 config = read(_default_cfg)