YAMLLoader.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. import os
  3. import yaml
  4. from core.Utils import Utils
  5. logging.basicConfig()
  6. logger = logging.getLogger("kalliope")
  7. class YAMLFileNotFound(Exception):
  8. pass
  9. class YAMLLoader:
  10. def __init__(self):
  11. pass
  12. @classmethod
  13. def get_config(cls, yaml_file):
  14. """
  15. Load settings file
  16. :return: cfg : the configuration file
  17. """
  18. # # Load settings.
  19. # __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
  20. # try:
  21. # with open(os.path.join(__location__, yaml_file)) as ymlfile:
  22. # cfg = yaml.load(ymlfile)
  23. # return cfg
  24. # except IOError:
  25. # raise YAMLFileNotFound("The file path %s does not exist" % yaml_file)
  26. current_dir = os.path.dirname(os.path.abspath(__file__))
  27. logger.debug("Current dir: %s " % current_dir)
  28. root_dir = os.path.join(current_dir, "../../")
  29. root_dir = os.path.normpath(root_dir)
  30. logger.debug("Root dir: %s " % root_dir)
  31. file_path_to_load = os.path.join(root_dir, yaml_file)
  32. logger.debug("File path to load: %s " % file_path_to_load)
  33. if os.path.isfile(yaml_file):
  34. data = IncludeLoader(open(file_path_to_load, 'r')).get_data()
  35. # print Utils.print_yaml_nicely(data)
  36. return data
  37. else:
  38. raise YAMLFileNotFound("File %s not found" % file_path_to_load)
  39. class IncludeLoader(yaml.Loader):
  40. def __init__(self, *args, **kwargs):
  41. super(IncludeLoader, self).__init__(*args, **kwargs)
  42. self.add_constructor('!include', self._include)
  43. if 'root' in kwargs:
  44. self.root = kwargs['root']
  45. elif isinstance(self.stream, file):
  46. self.root = os.path.dirname(self.stream.name)
  47. else:
  48. self.root = os.path.curdir
  49. def _include(self, loader, node):
  50. oldRoot = self.root
  51. filename = os.path.join(self.root, loader.construct_scalar(node))
  52. self.root = os.path.dirname(filename)
  53. data = yaml.load(open(filename, 'r'))
  54. self.root = oldRoot
  55. return data