Reputation: 35720
I have a directory plugins
containing plugins of my application, each plugin is a python file which defines a method handle
in it. the structure is like:
- main.py
- plugins
- hello.py
- foo.py
- bar.py
- ...
Now I'd like to import all modules in plugins
in main.py
with:
from plugins import *
however, I want to get a list of the modules, so I can loop through it, like:
for plugin in plugin_modules:
plugin.handle(data)
How could I do this?
Upvotes: 2
Views: 78
Reputation: 80346
Try pkgutil
:
import os.path, pkgutil
import mypackage
package = mypackage
mods = [n for _,n,_ in pkgutil.iter_modules([os.path.dirname(package.__file__)])]
for mod in mods:
package.__dict__.get(mod).handle(data)
Upvotes: 1
Reputation: 3638
simple but won't get everything:
import plugins
for i in range(len(plugins.__all__)):
getattr(plugins, plugins.__all__[i]).handle(data)
Upvotes: 0