Advertisement
Guest User

Untitled

a guest
Nov 20th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. class _NotFoundModuleError(Exception): pass
  2. _init_re = re.compile(r'^(.*)\{sep}__init__\.(\w+)$'.format(sep=os.sep))
  3. def import_path(path):
  4.     def _import_module(name):
  5.         try:
  6.             return importlib.import_module(name)
  7.         except ImportError as ex:
  8.             if ex.args[0] == "No module named '{}'".format(name):
  9.                 raise _NotFoundModuleError from ex
  10.             raise
  11.  
  12.     cwd = os.path.abspath(os.path.realpath(os.getcwd()))
  13.     path = os.path.abspath(os.path.realpath(path))
  14.  
  15.     paths = []
  16.     for p in sys.path:
  17.         p = os.path.abspath(os.path.realpath(p))
  18.         if path.startswith(p):
  19.             paths.append(p)
  20.     if not paths:
  21.         raise ImportError('unable to find module with path {!r}: not in a sys.path'.format(path))
  22.  
  23.     paths.sort(key=lambda x: len(x), reverse=True)
  24.  
  25.     init_match = _init_re.match(path)
  26.     if init_match:
  27.         path = init_match.group(1)
  28.     else:
  29.         path = path.rpartition('.')[0]
  30.  
  31.     was_in_cwd = False
  32.     for syspath in paths:
  33.         if syspath == cwd:
  34.             was_in_cwd = True
  35.             continue
  36.  
  37.         # Check that syspath is a proper directory prefix,
  38.         # i.e. tail starts with os.sep.
  39.         #
  40.         tail = path[len(syspath.rstrip(os.sep)):]
  41.         if tail[0] != os.sep:
  42.             tail = path
  43.  
  44.         modname = tail.strip(os.sep).replace(os.sep, '.')
  45.         try:
  46.             return _import_module(modname)
  47.         except _NotFoundModuleError:
  48.             pass
  49.  
  50.     if was_in_cwd:
  51.         modname = path[len(cwd):].strip(os.sep).replace(os.sep, '.')
  52.         try:
  53.             return _import_module(modname)
  54.         except _NotFoundModuleError:
  55.             pass
  56.  
  57.     raise ImportError('unable to find module with path {!r}'.format(path))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement