在Python中实现插件系统 [英] Implementing a Plugin System in Python

查看:263
本文介绍了在Python中实现插件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序(适用于Minecraft的服务器包装程序),希望可以通过插件进行扩展.我已经建立了一个可行的系统,但是从长远来看,我认为它可以使用改进.

I am writing an application (a server wrapper for Minecraft) that I wish to make extensible with plugins. I have a system in place that works, however I think that in the long run it could use improvement.

我现在所拥有的方式,应用程序在服务器类中调用"get_plugins"方法,该方法首先导入名为pluginutils.py的文件(pluginutils.py定义了所有插件子类的BasePlugin类),然后循环通过 cmds 目录中的每个.py文件,将其导入并检查它是否是BasePlugin的子类.如果是,它将实例存储在字典中,其关键字是插件中定义的 cmd 类变量.每当应用程序从服务器接收到命令时,它都会检查它是否是字典中的键,如果是,则运行存储在字典中的实例的start方法,并将从命令中获取的必要参数传递给该方法.

The way that I have it now, the application calls a "get_plugins" method in the server class that, first imports a file named pluginutils.py (pluginutils.py defines a BasePlugin class which all plugins subclass), and then loops through every .py file in the cmds directory, importing it and checking to see if it is a subclass of BasePlugin. If it is, it stores an instance of it in a dictionary, for which the key is a cmd class variable defined in the plugin. Whenever the application receives a command from the server it checks if it is a key in the dictionary and if so runs the start method of the instance stored in the dictionary, to which it passes the necessary arguments taken from the command.

虽然可行,但我觉得这是一种草率的做法.是否有更好的技术来实现与此类似的系统?我想自己写这个(我不想使用像zope.interface这样的东西),因为这是一种学习的经验.谢谢.

While this works, I feel like this is a sloppy way to do it. Are there any better techniques for implementing a system similar to this? I want to write this myself (I don't want to use anything like zope.interface) as this is a learning experience. Thanks.

推荐答案

我已经用不同的平台和语言编写了许多不同的插件体系结构,我会说,大多数插件系统是如何编写的.

Having written quite a few different plugin architectures in different platforms and languages, I will say that you are pretty much on track with how most plugins systems are written.

基本上可以归结为您的主机和您的插件需要某种通用合同才能使用;换句话说,您的主机需要对插件有足够的了解,以便它可以传递或共享该插件所需的任何公共资源,并且该插件需要对主机有足够的了解才能与这些资源进行交互.

Basically what it boils down to, is your host and your plugin need to have some kind of common contract to work with; in other words, your host needs to know enough about your plugin that it can pass along or share whatever common resources the plugin will need, and the plugin needs to know enough about the host to interact with those resources.

使用基类和派生类来实现这一点是一种非常常见的方法.

Implementing this using a base class and a derived class as you have done is a very common methodology.

这篇关于在Python中实现插件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆