Update xtendr/import os import importlib.util from abc import ABC, abstractmethod # Define the interface that all plugins must implement class PluginInterface(ABC): @abstractmethod def execute(self, *args, **kwargs): """ Execute the plugcore.py

This commit is contained in:
2024-12-06 18:27:11 +01:00
parent 9a41df6c57
commit 12fb4e3005
2 changed files with 70 additions and 0 deletions

View File

View File

@@ -0,0 +1,70 @@
import os
import importlib.util
from abc import ABC, abstractmethod
# Define the interface that all plugins must implement
class PluginInterface(ABC):
@abstractmethod
def execute(self, *args, **kwargs):
"""
Execute the plugin's functionality.
"""
pass
class PluginManager:
def __init__(self, plugins_dir="plugins"):
"""
Initialize the plugin manager.
:param plugins_dir: Directory containing plugin modules.
"""
self.plugins_dir = plugins_dir
self.plugins = {}
def load_plugins(self):
"""
Load all plugins from the plugins directory.
"""
if not os.path.exists(self.plugins_dir):
os.makedirs(self.plugins_dir)
print(f"Created plugins directory at {self.plugins_dir}.")
return
for filename in os.listdir(self.plugins_dir):
if filename.endswith(".py"):
plugin_name = os.path.splitext(filename)[0]
plugin_path = os.path.join(self.plugins_dir, filename)
spec = importlib.util.spec_from_file_location(plugin_name, plugin_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Check if the module contains a valid plugin
for attr_name in dir(module):
attr = getattr(module, attr_name)
if isinstance(attr, type) and issubclass(attr, PluginInterface) and attr is not PluginInterface:
self.plugins[plugin_name] = attr()
print(f"Loaded plugin: {plugin_name}")
def execute_plugin(self, plugin_name, *args, **kwargs):
"""
Execute a plugin by name.
:param plugin_name: Name of the plugin to execute.
"""
plugin = self.plugins.get(plugin_name)
if plugin:
return plugin.execute(*args, **kwargs)
else:
print(f"Plugin '{plugin_name}' not found.")
# Example of how the PluginManager would be used
if __name__ == "__main__":
manager = PluginManager()
manager.load_plugins()
# Execute a plugin (replace 'example_plugin' with your actual plugin name)
result = manager.execute_plugin('example_plugin', param1="Hello", param2="World")
print("Result:", result)