Dynamic class loading in Python 2.6: RuntimeWarning: Parent module 'plugins' not found while handling absolute import

前端 未结 5 2091
不知归路
不知归路 2020-12-30 23:37

I am working on a plugin system where plugin modules are loaded like this:

def load_plugins():
   plugins=glob.glob(\"plugins/*.py\")
   instances=[]
   for         


        
5条回答
  •  再見小時候
    2020-12-30 23:58

    The Python imp documentation has been updated since this was answered. It now addresses this issue specifically in the find_module() method.

    This function does not handle hierarchical module names (names containing dots). In order to find P.M, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__. When P itself has a dotted name, apply this recipe recursively.

    Note that P.__path__ is already a list when supplying it to find_module(). Also note what the find_module() documentation says about finding packages.

    If the module is a package, file is None, pathname is the package path and the last item in the description tuple is PKG_DIRECTORY.

    So from the OP's question, to import the plugin without the RuntimeError warnings, follow the directions in the updated Python documentation:

    # first find and load the package assuming it is in
    # the current working directory, '.'
    
    f, file, desc = imp.find_module('plugins', ['.'])
    pkg = imp.load_module('plugins', f, file, desc)
    
    # then find the named plugin module using pkg.__path__
    # and load the module using the dotted name
    
    f, file, desc = imp.find_module(name, pkg.__path__)
    plugin = imp.load_module('plugins.' + name, f, file, desc)
    

提交回复
热议问题