Solved bug in python loader related to import of files and sys.path.
@@ -2107,6 +2107,8 @@ int py_loader_impl_initialize_import(loader_impl_py py_impl)
"import sys\n"
"import importlib.util\n"
"import importlib\n"
+ "from pathlib import Path\n"
+ "\n"
"def load_from_spec(module_name, spec):\n"
" m = importlib.util.module_from_spec(spec)\n"
" spec.loader.exec_module(m)\n"
@@ -2114,6 +2116,7 @@ int py_loader_impl_initialize_import(loader_impl_py py_impl)
" return m\n"
"\n"
"def load_from_path(module_name, path = None):\n"
+ " search_location = None\n"
" try:\n"
" if path == None:\n"
" if module_name in sys.modules:\n"
@@ -2124,15 +2127,28 @@ int py_loader_impl_initialize_import(loader_impl_py py_impl)
" return FileNotFoundError('Module ' + module_name + ' could not be found')\n"
" return load_from_spec(module_name, spec)\n"
" else:\n"
- " spec = importlib.util.spec_from_file_location(module_name, path)\n"
+ " current_search_location = str(Path(path).parent.absolute())\n"
+ " if not current_search_location in sys.path:\n"
+ " search_location = current_search_location\n"
+ " sys.path.insert(0, current_search_location)\n"
+ " spec = importlib.util.spec_from_file_location(module_name, path, submodule_search_locations=[current_search_location])\n"
" if spec is None:\n"
+ " if search_location is not None:\n"
+ " sys.path.pop(0)\n"
" return FileNotFoundError('File ' + path + ' could not be found')\n"
- " return load_from_spec(module_name, spec)\n"
+ " module = load_from_spec(module_name, spec)\n"
+ " if search_location is not None:\n"
+ " sys.path.pop(0)\n"
+ " return module\n"
" except FileNotFoundError as e:\n"
+ " if search_location is not None:\n"
+ " sys.path.pop(0)\n"
" return e\n"
" except Exception as e:\n"
" import traceback\n"
" print(traceback.format_exc())\n"
+ " if search_location is not None:\n"
+ " sys.path.pop(0)\n"
" return e\n"
#elif PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 3
// TODO: Not tested
