congdong007

Penetration Test、Software Developer

0%

A Simple Plugin System by Python

Due to the requirements of my work, I needed to design an open software system, and immediately thought of the Python language. As a result, I designed a simple and easily extensible plugin system.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#main.py


import importlib

class PluginManager:
def __init__(self):
self.plugins = []
self.func_name = "MyPlugin"

def load_plugin(self, plugin_name):
try:
plugin_module = importlib.import_module(f'plugins.{plugin_name}')
plugin_instance = getattr(plugin_module, self.func_name)()
self.plugins.append(plugin_instance)
print(f"plugin {plugin_name} loaded.")
except ImportError:
print(f"Load plugin {plugin_name} failed.")

def run_plugins(self):
for plugin in self.plugins:
plugin.run()


if __name__ == "__main__":
manager = PluginManager()

while True:
print("1. Add Plugin")
print("2. Run Plugin")
print("3. Quit")
choice = input("Your Select: ")

if choice == "1":
plugin_name = input("Please input the name of plugin: ")
manager.load_plugin(plugin_name)

elif choice == "2":
manager.run_plugins()

elif choice == "3":
break

Then, you create a directory named ‘plugins.’ In this directory, you can add your plugin, which must define a class named ‘MyPlugin’ and must have a function named ‘run’. Here is the simple code:

1
2
3
4
5
6
7
#my_plugin

class MyPlugin:
def __init__(self):
pass
def run(self):
print("MyPlugin is running")

The following is the running process:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1. Add Plugin
2. Run Plugin
3. Quit
Your Select: 1
Please input the name of plugin: my_plugin
plugin my_plugin loaded.
1. Add Plugin
2. Run Plugin
3. Quit
Your Select: 2
MyPlugin is running
1. Add Plugin
2. Run Plugin
3. Quit
Your Select: 3
PS C:\Users\xxx\Desktop\yyy\plugin-system>

You can use this model to design a big and an opened software system.