初步实现插件系统

This commit is contained in:
lzybetter
2024-03-18 22:14:13 +08:00
parent 0b49d4f2a3
commit b2065d1d01
7 changed files with 81 additions and 35 deletions

1
.gitignore vendored
View File

@@ -31,6 +31,7 @@ pip-selfcheck.json
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.idea
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml

5
.idea/misc.xml generated
View File

@@ -1,6 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7 (myAssistant)" project-jdk-type="Python SDK" />
<component name="Black">
<option name="sdkName" value="Python 3.7 (myAssistant)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (myAssistant)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>

2
.idea/myAssistant.iml generated
View File

@@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.7 (myAssistant)" jdkType="Python SDK" />
<orderEntry type="jdk" jdkName="Python 3.10 (myAssistant)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

10
main.py
View File

@@ -0,0 +1,10 @@
from util.PluginManager import PluginManager
if __name__ == "__main__":
manager = PluginManager()
# Load and execute plugins
manager.load_plugins()
plugin_names = manager.get_plugin_name_list()
print(plugin_names)

58
util/PluginManager.py Normal file
View File

@@ -0,0 +1,58 @@
import importlib.util
import os
from util.base_plugin import BasePlugin
class PluginManager:
PLUGIN_DIR = "custom_plugins"
def __init__(self):
self.plugins = {}
self.plugin_dir = PluginManager.PLUGIN_DIR
def load_plugins(self):
for root, dirs, files in os.walk(self.plugin_dir):
for file in files:
if file.endswith(".py"):
plugin_name = os.path.splitext(file)[0]
plugin_path = os.path.join(root, file)
print(plugin_name)
self.load_plugin(plugin_name, plugin_path)
def load_plugin(self, plugin_name, plugin_path):
spec = importlib.util.spec_from_file_location(plugin_name, plugin_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
for member_name in dir(module):
member = getattr(module, member_name)
if callable(member) and hasattr(member, "__bases__") and BasePlugin in member.__bases__:
print(member)
self.plugins[plugin_name] = member()
print(f"Plugin '{plugin_name}' loaded successfully.")
def execute_plugins(self, *args, **kwargs):
for plugin_name, plugin_instance in self.plugins.items():
print(f"Executing plugin '{plugin_name}':")
plugin_instance.run_plugin(self.callback, *args, **kwargs)
def execute_plugin(self, plugin_name, *args, **kwargs):
if plugin_name in self.plugins:
print(f"Executing plugin '{plugin_name}':")
self.plugins[plugin_name].run_plugin(self.callback, *args, **kwargs)
else:
print(f"Plugin '{plugin_name}' not found.")
def get_plugin_name_list(self):
return [plugin[0] for plugin in self.plugins.items()]
def callback(self, result):
print(f"Plugin '{result['plugin_name']}' returned:")
print(f"Success: {result['success']}")
if result['success']:
print(f"Result: {result['result']}")
else:
print(f"Error: {result['error']}")

7
util/base_plugin.py Normal file
View File

@@ -0,0 +1,7 @@
class BasePlugin:
def __init__(self, plugin_name, title):
self.plugin_name = plugin_name
self.title = title
def run_plugin(self, callback):
raise NotImplementedError("Subclasses must implement run_plugin method")

View File

@@ -1,33 +0,0 @@
class BasePlugin:
def __init__(self):
self.__plugin_name = ""
def get_result(self):
"""
用以返回插件的结果,所有插件都必须通过该方法返回结果
返回结果的类型必须是指定的类型
:return:
"""
raise NotImplemented
class FinanceValue:
def __init__(self):
self.__name = ""
self.__value = ""
def set_name(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_value(self, value):
self.__value = value
def get_value(self):
return self.__value