【问题标题】:Unable to find the functions defined in dynamically loaded module找不到动态加载模块中定义的函数
【发布时间】:2012-01-23 07:42:12
【问题描述】:

我对 python 很陌生。这是我遇到的问题。 我已将 builtin._import_ 与从字符串加载模块的自定义挂钩挂钩。

def import_hook(name, globals=None, locals=None, fromlist=None):
    if name in sys.modules:
            obj = sys.modules[name]
            return obj
    #Make sure we hook only for modules which start with ajay    
    if name.startswith("ajay"):
        statement = '''
print 'inside the ajay module'
def ajay_func():
    print 'inside the func'
'''
        mod = imp.new_module(name)
        mod.__file__ = name
        compiled = compile(statement, '<string>', 'exec')
        exec compiled in mod.__dict__
        sys.modules[name] = mod
        return mod

    return original_import(name, globals, locals, fromlist)

然后我在函数中使用这个钩子,它正在加载一个模块并在 exec 语句中调用它的函数。

original_import = __builtin__.__import__
def test(request):
    statement = '''
import sys
import ajay
def ILessons_1(request):
    ajay.ajay_func()
'''
    try:
        __builtin__.__import__ = import_hook
        compiled = compile(statement, '<string>', 'exec')
        exec (compiled, globals(), locals())  #in statement_module.__dict__
        ajay.ajay_func()
        return ILessons_1(request);
    finally:
        __builtin__.__import__ = original_import 
        pass 

当我运行此代码时,在“return ILessons_1(request);”行中出现错误“未定义全局名称 'ajay'”。有趣的是,python 能够在这条线的上方解析 ajay。我很确定我在 exec 语句中犯了一些错误,但无法弄清楚。

有人能帮我解决这个问题吗? 谢谢

【问题讨论】:

    标签: python import-hooks


    【解决方案1】:

    这里注意到几个问题:

    1) globalslocals 是内置函数名,不应将它们用作变量名。

    2) 可能是一个错误? (在ubuntu下用python 2.7.1测试过)

    考虑以下代码(注意 exec 语句):

    def outer_function():
        foo = "foobar"
        statement = '''
    def inner_function():
        print foo
    '''
        #exec statement in globals(), locals()
        exec statement in globals().update(locals())
        inner_function()
    
    outer_function()
    

    此处注释的字符串(在 in 之后带有 2 个参数的 exec)将无法按照in the documentation 中的描述工作,并导致:

    NameError: global name 'foo' is not defined
    

    但是可以手动组合全局变量+局部变量并将它们传递给 exec(在我的示例中,注释后的下一个字符串)。对我来说似乎是一种解决方法。

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 2015-06-05
      • 2011-11-18
      • 2017-10-17
      • 1970-01-01
      • 2016-12-28
      • 2021-12-23
      • 2014-02-22
      相关资源
      最近更新 更多