我对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)
然后我在函数中使用这个钩子,它正在加载一个模块并在 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 语句中犯了一些错误,但无法弄清楚。
有人可以帮我解决这个问题。谢谢