Reputation: 1091
I am implementing an import hook that automatically installs missing modules using pip.
So far it is working OK with simple modules (that have only one level), for instance unipath
. However if I try to use it with multilevel imports, such as zope.interface
the importer only gets the first part (zope
). That causes it to fail as zope
does not exist in PyPI.
Any idea of how to achieve getting the full module's name when importing it?
Here some code:
class PipLoader(object):
def __init__(self):
self.module = None
def find_module(self, name, path):
print "Will install module {}".format(name)
self.module = None
sys.meta_path.remove(self)
try:
pip_install(name)
self.module = importlib.import_module(name)
finally:
sys.meta_path.append(self)
return self
def load_module(self, name):
if not self.module:
raise ImportError("Unable to load module")
module = self.module
sys.modules[name] = module
return module
def install():
sys.meta_path.append(PipLoader())
Upvotes: 2
Views: 449
Reputation: 14873
If you replace __import__
then you get the module globals that of the module imports and much more information.
Upvotes: 2