Dynamic loading of python modules

后端 未结 6 1558
囚心锁ツ
囚心锁ツ 2020-11-27 13:01

In python how do you dynamically add modules to a package while your program is running.

I want to be able to add modules to the package directory from an outside pr

6条回答
  •  囚心锁ツ
    2020-11-27 13:29

    Bastien already answered the question, anyway you may find useful this function I use to load all the modules from a subfolder in a dictionary:

    def loadModules():
        res = {}
        import os
        # check subfolders
        lst = os.listdir("services")
        dir = []
        for d in lst:
            s = os.path.abspath("services") + os.sep + d
            if os.path.isdir(s) and os.path.exists(s + os.sep + "__init__.py"):
                dir.append(d)
        # load the modules
        for d in dir:
            res[d] = __import__("services." + d, fromlist = ["*"])
        return res
    

    This other one is to instantiate an object by a class defined in one of the modules loaded by the first function:

    def getClassByName(module, className):
        if not module:
            if className.startswith("services."):
                className = className.split("services.")[1]
            l = className.split(".")
            m = __services__[l[0]]
            return getClassByName(m, ".".join(l[1:]))
        elif "." in className:
            l = className.split(".")
            m = getattr(module, l[0])
            return getClassByName(m, ".".join(l[1:]))
        else:
            return getattr(module, className)
    

    A simple way to use those functions is this:

    mods = loadModules()
    cls = getClassByName(mods["MyModule"], "submodule.filepy.Class")
    obj = cls()
    

    Obviously you can replace all the "services" subfolder references with parameters.

提交回复
热议问题