Load modules from a Python file Args: file_path (`str`): The python file path. Returns: `Any`: The loaded module.
(file_path: str)
| 51 | |
| 52 | |
| 53 | def load_from_file(file_path: str): |
| 54 | """ |
| 55 | Load modules from a Python file |
| 56 | |
| 57 | Args: |
| 58 | file_path (`str`): The python file path. |
| 59 | |
| 60 | Returns: |
| 61 | `Any`: The loaded module. |
| 62 | """ |
| 63 | module_name = os.path.splitext(os.path.basename(file_path))[0] |
| 64 | |
| 65 | full_module_name = f"trinity.plugins.{module_name}" |
| 66 | |
| 67 | spec = importlib.util.spec_from_file_location(full_module_name, file_path) |
| 68 | if spec is None: |
| 69 | raise ImportError(f"Cannot load module from {file_path}") |
| 70 | |
| 71 | module = importlib.util.module_from_spec(spec) |
| 72 | |
| 73 | module.__package__ = "trinity.plugins" |
| 74 | |
| 75 | spec.loader.exec_module(module) |
| 76 | |
| 77 | if full_module_name in sys.modules: |
| 78 | raise ImportError(f"Module {module_name} already exists.") |
| 79 | sys.modules[full_module_name] = module |
| 80 | try: |
| 81 | shutil.copy2(file_path, Path(__file__).parent.parent / "plugins") |
| 82 | except shutil.SameFileError: |
| 83 | pass |
| 84 | return module |
no outgoing calls
no test coverage detected