A very Simple and Stupid plugin system in python
source link: https://blog.mathieu-leplatre.info/a-very-simple-and-stupid-plugin-system-in-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
A very Simple and Stupid plugin system in python
Fri 02 September 2011Two convenience functions for listing and importing python modules :
# utils.py import os def plugins_list(plugins_dirs): """ List all python modules in specified plugins folders """ for path in plugins_dirs.split(os.pathsep): for filename in os.listdir(path): name, ext = os.path.splitext(filename) if ext.endswith(".py"): yield name def import_plugins(plugins_dirs, env): """ Import modules into specified environment (symbol table) """ for p in plugins_list(plugins_dirs): m = __import__(p, env) env[p] = m
And now use import_plugins() wherever you need to use them !
# yourapp.py import os from utils import import_plugins plugins_dirs = "plugins/:module/plugins/" sys.path.extend(plugins_dirs.split(os.pathsep)) import_plugins(plugins_dirs, globals())
Note that in order to list all sub-classes of a specific one, you can use this recursive function.
That's all folks !
It is very simple and very stupid, but useful :) You might now want to have a look at serious stuff like Yapsy or PkgResouces.
#python - Posted in the Dev category
© Copyright 2020 by Mathieu Leplatre. mnmlist Theme
Content licensed under the Creative Commons attribution-noncommercial-sharealike License.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK