简体   繁体   中英

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 statement 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 (eg __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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM