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

前端 未结 5 2059
不知归路
不知归路 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:56

    If the directory plugins were a real package (contained __init__.py fine), you could easily use pkgutils to enumerate its plugin files and load them.

    import pkgutil
    # import our package
    import plugins
    list(pkgutil.iter_modules(plugins.__path__))
    

    However, it can work without a plugin package anyway, try this:

    import pkgutil
    list(pkgutil.iter_modules(["plugins"]))
    

    Also it is possible to make a package that only exists at runtime:

    import types
    import sys
    plugins = types.ModuleType("plugins")
    plugins.__path__ = ["plugins"]
    
    sys.modules["plugins"] = plugins
    import plugins.testplugin
    

    However that hack that was mostly for fun!

提交回复
热议问题