2012-01-23 75 views
0

我对python很陌生。这是我遇到的问题。 我已经迷上内建 ._ 导入 _与我的自定义挂钩从一个字符串加载模块。无法找到动态加载模块中定义的功能

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 

当我运行这段代码,我得到错误行“全局名称‘阿贾伊’没有定义”,“返回ILessons_1(要求);”。有趣的是python能够在这条线上方解析ajay。林相当肯定我在执行语句中犯了一些错误,但一直无法弄清楚。

有些请帮我解决这个问题。 感谢

回答

0

这里注意到几个问题:

1)globalslocals是内置的函数名,你不应该使用它们作为变量名。

2)可能是一个错误? (与Python 2.7.1测试在Ubuntu下)

考虑下面的代码(注意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描述,并导致:

NameError: global name 'foo' is not defined 

但一个可以手动合并全局+当地人的在我的例子评论之后将它们传递给exec(下一个字符串)。看起来像我的解决方法。

相关问题