开发者

How to provide an API to extend a Python program with plugins?

I was wondering how I can provide an API for my Python program to enable others to extend it with plugins. I thought about something like from myProgram.plugins import aClassToExtendByOthers, registerThatClass. But I have no idea how to provide this.

I could use an exec state开发者_如何学Cment within my loadPlugins function for every plugin in the plugins-folder, but this would not enable importing stuff I would like to provide for people to write those plugins.


For a system that I use in several of my programs, I define a directory of plugins, and provide a base plugin class for all plugins to subclass. I then import all modules in the directory, and selectively initialize (by checking to see if they subclass my base plugin class), and store instances of plugins in a dictionary (or list). I have found that the command dispatch pattern has worked effectively for me as a way to structure the plugins and pass events. The base plugin (or another optional interface class) can provide the methods that the plugin needs to interact with the application. I hope this helps. It may not be the best way to do it, but it has worked for me.

In addition, you could do additional filtering, such as requiring plugin files to have a prefix (e.g. __plug_file.py__ and __plug_other.py__).


you can use imp module (see docs.python.org)

sys.path.insert(0, pluginsDir)
lst = map(lambda x: os.path.splitext(os.path.basename(x))[0], glob.glob(os.path.join(pluginsDir, "*.py")))
for module in lst:
try:
  f, fn, d = imp.find_module(module,[pluginsDir])
  loaded = imp.load_module(module, f, fn, d)

for fully functional example see the loader of ojuba control center

http://git.ojuba.org/cgit/occ/tree/OjubaControlCenter/loader.py

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜