【问题标题】:How is calling module and function by string handled in python?python中如何通过字符串调用模块和函数?
【发布时间】:2011-10-02 08:49:20
【问题描述】:

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

假设我们可能还必须执行 foo 的导入(或从 bar 进口 foo)?

【问题讨论】:

标签: python


【解决方案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()

【讨论】:

    【解决方案3】:

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

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

    (David 几乎做到了,但我认为他的示例更适合您想要重新定义正常导入过程 - 例如从 zip 文件加载)

    【讨论】:

    • 经过一番哄骗后工作,应该给出一个更好的例子。我看不到只导入请求的功能的方法。 >>> a = import__("foo.bar", globals(), locals(), ['baz',], -1) >>> dir(a) ['__builtins', 'doc', 'file', 'name', 'package', 'baz', 'wok ', '喇叭'] >>>
    • 我终于重温了这个。我接受了这一点,因为它让我朝着我想要的方向前进。我已经发布了我想出的最终解决方案
    • 我还建议查看importlib:from importlib import import_module,然后在您的代码中使用import_module(...)。这是一个简化的__import__,没有所有参数。
    【解决方案4】:

    这是我最终想出的从点名中取出我想要的功能

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 2010-09-05
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      相关资源
      最近更新 更多