from importlib.util import module_from_spec, spec_from_file_location from os import getcwd, path, walk #================================================================================= # Import functions # Took from https://stackoverflow.com/a/57892961 def get_py_files(src): cwd = getcwd() py_files = [] for root, dirs, files in walk(src): for file in files: if file.endswith(".py"): py_files.append(path.join(cwd, root, file)) return py_files def dynamic_import(module_name, py_path): try: module_spec = spec_from_file_location(module_name, py_path) module = module_from_spec(module_spec) # type: ignore module_spec.loader.exec_module(module) # type: ignore return module except SyntaxError: print(f"Could not load extension {module_name} due to invalid syntax. Check logs/errors.log for details.", flush=True) return except Exception as exp: print(f"Could not load extension {module_name} due to {exp}", flush=True) return def dynamic_import_from_src(src, star_import = False): my_py_files = get_py_files(src) for py_file in my_py_files: module_name = path.split(py_file)[-1][:-3] print(f"Importing {module_name} extension...", flush=True) imported_module = dynamic_import(module_name, py_file) if imported_module != None: if star_import: for obj in dir(imported_module): globals()[obj] = imported_module.__dict__[obj] else: globals()[module_name] = imported_module print(f"Successfully loaded {module_name} extension", flush=True) return #=================================================================================