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。林相当肯定我在执行语句中犯了一些错误,但一直无法弄清楚。
有些请帮我解决这个问题。 感谢