首页 文章

如何在python中处理字符串调用模块和函数?

提问于
浏览
5

Calling a function of a module from a string with the function's name in Python向我们展示了如何使用getattr(“ bar ”)()来调用函数,但这假设我们已经导入了模块 foo .

假如我们可能还必须执行 foo (或 bar import foo )的导入,那么我们将如何调用 "foo.bar" 的执行呢?

4 回答

  • 0

    使用 __import__(....) 函数:

    http://docs.python.org/library/functions.html#import

    (David几乎拥有它,但我认为如果你想重新定义正常的导入过程,例如从zip文件加载,他的例子更适合做什么)

  • 3

    您可以使用imp模块中的 find_moduleload_module 来加载在执行时确定其名称和/或位置的模块 .

    文档主题末尾的示例说明了如何:

    import imp
    import sys
    
    def __import__(name, globals=None, locals=None, fromlist=None):
        # Fast path: see if the module has already been imported.
        try:
            return sys.modules[name]
        except KeyError:
            pass
    
        # If any of the following calls raises an exception,
        # there's a problem we can't handle -- let the caller handle it.
    
        fp, pathname, description = imp.find_module(name)
    
        try:
            return imp.load_module(name, fp, pathname, description)
        finally:
            # Since we may exit via an exception, close fp explicitly.
            if fp:
                fp.close()
    
  • 2

    这是我最终想出的功能,以便从虚线名称中获取我想要的功能

    from string import join
    
    def dotsplit(dottedname):
        module = join(dottedname.split('.')[:-1],'.')
        function = dottedname.split('.')[-1]
        return module, function
    
    def load(dottedname):
        mod, func = dotsplit(dottedname)
        try:
            mod = __import__(mod, globals(), locals(), [func,], -1)
            return getattr(mod,func)
        except (ImportError, AttributeError):
            return dottedname
    
  • 1

相关问题