Skip to content Skip to sidebar Skip to footer

Plugin Manager In Python

I am relatively new to python (already did some 1h scripts like a little webserver or a local network chat) and want to program a plugin manager in it. My idea is, that there is an

Solution 1:

At the most basic level, first of all, you want to provide a basic Plugin class which is a base for all plugins written for your application.

Next we need to import them all.

class PluginLoader():
    def __init__(self, path):
        self.path = path

    def __iter__(self):
        for (dirpath, dirs, files) in os.walk(self.path):
            if not dirpath in sys.path:
                sys.path.insert(0, dirpath)
        for file in files:
                (name, ext) = os.path.splitext(file)
                if ext == os.extsep + "py":
                    __import__(name, None, None, [''])
        for plugin in Plugin.__subclasses__():
            yield plugin

In Python 2.7 or 3.1+, instead of __import__(name, None, None, ['']), consider:

import importlib  # just once
importlib.import_module(name)

This loads every plugin file and gives us all plugins. You would then select your plugins as you saw fit, and then use them:

from multiprocessing import Process, Pipe

plugins = {}

for plugin in PluginLoader("plugins"):
    ... #select plugin(s)
    if selected:
        plugins[plugin.__name__], child = Pipe()
        p = Process(target=plugin, args=(child,))
        p.start()

...

for plugin in plugins.values():
    plugin.put("EventHappened")

...

for plugin in plugins.values():
    event = plugin.get(False)
    if event:
       ... #handle event

This is just what comes to mind at first. Obviously much more would be needed for flesh this out, but it should be a good basis to work from.


Solution 2:

Check yapsy plugin https://github.com/tibonihoo/yapsy. This should work for you


Post a Comment for "Plugin Manager In Python"