AbdealiJK

import module using file path

Aug 23rd, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. def _import_module(file_path):
  2.     if not os.path.exists(file_path):
  3.         raise ImportError
  4.  
  5.     module_name = os.path.splitext(os.path.basename(file_path))[0]
  6.     module_dir = os.path.dirname(file_path)
  7.  
  8.     # Ugly inconsistency: Python will insist on correctly cased module names
  9.     # independent of whether the OS is case-sensitive or not.
  10.     # We want all cases to match though.
  11.     if platform.system() == 'Windows':  # pragma: nocover
  12.         for cased_file_path in os.listdir(module_dir):
  13.             cased_module_name = os.path.splitext(cased_file_path)[0]
  14.             if cased_module_name.lower() == module_name.lower():
  15.                 module_name = cased_module_name
  16.                 break
  17.  
  18.     if sys.version_info < (3, 5):
  19.         from importlib.machinery import SourceFileLoader
  20.         module = SourceFileLoader(module_name, file_path).load_module()
  21.     else:
  22.         import importlib.util
  23.         spec = importlib.util.spec_from_file_location(module_name, file_path)
  24.         module = importlib.util.module_from_spec(spec)
  25.         spec.loader.exec_module(module)
  26.  
  27.     return module
Add Comment
Please, Sign In to add comment