import_path.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. import importlib.machinery
  3. import importlib.util
  4. import os
  5. import sys
  6. root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  7. def import_path(path):
  8. '''
  9. https://stackoverflow.com/questions/2601047/import-a-python-module-without-the-py-extension
  10. https://stackoverflow.com/questions/31773310/what-does-the-first-argument-of-the-imp-load-source-method-do
  11. '''
  12. module_name = os.path.basename(path).replace('-', '_')
  13. spec = importlib.util.spec_from_loader(
  14. module_name,
  15. importlib.machinery.SourceFileLoader(module_name, path)
  16. )
  17. module = importlib.util.module_from_spec(spec)
  18. spec.loader.exec_module(module)
  19. sys.modules[module_name] = module
  20. return module
  21. def import_path_relative_root(basename):
  22. return import_path(os.path.join(root_dir, basename))
  23. def import_path_main(basename):
  24. '''
  25. Import an object of the Main class of a given file.
  26. By convention, we call the main object of all our CLI scripts as Main.
  27. '''
  28. return import_path_relative_root(basename).Main()