找不到在动态加载的modu中定义的函数

2024-09-28 01:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生。这是我遇到的问题。 我已经用我的自定义钩子钩住了内建函数.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)

然后我使用这个hook-in函数加载一个模块并在exec语句中调用它的函数。在

^{pr2}$

当我运行这段代码时,在“return ILessons_1(request);”行中出现错误“global name‘ajay’is not defined”。有趣的是python能够在这行上面的行中解析ajay。我很确定我在执行官的声明中犯了一些错误,但还没有弄清楚。在

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


Tags: 模块nameinimportnonemodulesmodreturn
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:11

注意到以下几个问题:

1)globals和{}是内置函数名,不应将它们用作变量名。在

2)可能是虫子?(在ubuntu下用Python2.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()

这里注释的字符串(exec在后有2个参数)将不能像在in the documentation中描述的那样工作,并导致:

^{pr2}$

但可以手动组合全局参数+局部变量并将它们传递给exec(在我的示例中,注释后面的下一个字符串)。在我看来是个变通办法。在

相关问题 更多 >

    热门问题