I am trying to import modules in Python dynamically. That means - I have a Python package with modules inside. Without specifying the modules names, I want to keep a dictionary of each module's name to the pointer to this module.
I tried to use the suggestion from this discussion
My directory is:
foo/
__init__.py
bar1.py
bar2.py
the script I use is:
import pkgutil
import foo
for importer, name, ispkg in pkgutil.iter_modules(foo.__path__, foo.__name__ + "."):
print "Found submodule %s (is a package: %s)" % (name, ispkg)
module = __import__(name)
print "Imported", module
The output I get for the first iteration is:
Found submodule foo.bar1 (is a package: False)
Imported <module 'foo' from '/path/to/foo/__init__.pyc'>
So instead of getting my bar1 module using this, I get the foo package with the import.
How can I get the bar1 and bar2 modules?
Other methods are welcome if the use of pkgutil is not right.