Plugin manager in python

前端 未结 2 1485
被撕碎了的回忆
被撕碎了的回忆 2021-02-11 02:25

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

相关标签:
2条回答
  • 2021-02-11 02:44

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

    0 讨论(0)
  • 2021-02-11 03:10

    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.

    0 讨论(0)
提交回复
热议问题