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

时间:2011-07-10 19:14:06

标签: python

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

我们如何才能要求执行“foo.bar”,假设我们可能还必须执行 foo 的导入(或来自< strong> bar 导入 foo )?

4 个答案:

答案 0 :(得分:3)

使用__import__(....)功能:

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

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

答案 1 :(得分:2)

您可以使用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 :(得分:1)

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

中获取我想要的功能
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

答案 3 :(得分:0)