utils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import inspect
  2. import logging
  3. import os
  4. logging.basicConfig()
  5. logger = logging.getLogger("kalliope")
  6. def get_root_kalliope_path():
  7. # here we are in /an/unknown/path/kalliope/core/ConfigurationManager
  8. current_script_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
  9. # get parent dir. Now we are in /an/unknown/path/kalliope
  10. kalliope_root_path = os.path.normpath(current_script_path + os.sep + os.pardir + os.sep + os.pardir)
  11. return kalliope_root_path
  12. def get_real_file_path(file_path_to_test):
  13. """
  14. Try to return a full path from a given <file_path_to_test>
  15. If the path is an absolute on, we return it directly.
  16. If the path is relative, we try to get the full path in this order:
  17. - from the current directory where kalliope has been called + the file_path_to_test.
  18. Eg: /home/me/Documents/kalliope_config
  19. - from /etc/kalliope + file_path_to_test
  20. - from the default file passed as <file_name> at the root of the project
  21. :param file_path_to_test file path to test
  22. :type file_path_to_test: str
  23. :return: absolute path to the file file_path_to_test or None if is doen't exist
  24. """
  25. if not os.path.isabs(file_path_to_test):
  26. path_order = {
  27. 1: os.getcwd() + os.sep + file_path_to_test,
  28. 2: "/etc/kalliope" + os.sep + file_path_to_test,
  29. 3: get_root_kalliope_path() + os.sep + file_path_to_test
  30. }
  31. for key in sorted(path_order):
  32. new_file_path_to_test = path_order[key]
  33. logger.debug("Try to load file from %s: %s" % (key, new_file_path_to_test))
  34. if os.path.isfile(new_file_path_to_test):
  35. logger.debug("File found in %s" % new_file_path_to_test)
  36. return new_file_path_to_test
  37. else:
  38. if os.path.isfile(file_path_to_test):
  39. return file_path_to_test
  40. else:
  41. return None