How can I import a python module function dynamically?

后端 未结 4 1827
春和景丽
春和景丽 2021-02-01 18:31

Assuming my_function() is located in my_apps.views I would like to import my_function dynamically without using something like exec or

4条回答
  •  無奈伤痛
    2021-02-01 19:06

    I just wrote this code and seems what a lot of people need, so even if later i show it

    def my_import(module_name,func_names = [],cache = False):
        if module_name in globals() and cache:
            return True
        try: 
            m = __import__(module_name, globals(), locals(), func_names, -1)
            if func_names:
                for func_name in func_names:
                    globals()[func_name] = getattr(m,func_name)
            else:
                globals()[module_name] = m
            return True
        except ImportError:
            return False
    def my_imports(modules):
        for module in modules:
            if type(module) is tuple:
                name = module[0]
                funcs = module[1]
            else:
                name = module
                funcs = []
            if not my_import(name, funcs):
                 return module
        return ''
    
    def checkPluginsImports(plugin,modules):
        c = my_imports(modules)
        if c:
            print plugin +" has errors!: module '"+c+"' not found"
    
    # example: file test.py with "x" function
    def d():
        checkPluginsImports('demoPlugin',[('test',['x'])])
    
    d()
    x()
    

提交回复
热议问题