Dynamic loading of python modules

后端 未结 6 1540
囚心锁ツ
囚心锁ツ 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:34

    One trick with Bastien's answer... The __import__() function returns the package object, not the module object. If you use the following function, it will dynamically load the module from the package and return you the module, not the package.

    def my_import(name):
        mod = __import__(name)
        components = name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        return mod
    

    Then you can do:

    mod = my_import('package.' + name)
    mod.doSomething()
    

提交回复
热议问题