Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to find the functions defined in dynamically loaded module
    text
    copied!<p>I'm very new to python. Here is the problem Im having. I have hooked the <strong>builtin</strong>._<em>import</em>_ with my custom hook which loads a module from a string.</p> <pre><code>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, '&lt;string&gt;', 'exec') exec compiled in mod.__dict__ sys.modules[name] = mod return mod return original_import(name, globals, locals, fromlist) </code></pre> <p>Then I use this hook in function which is loading a module and calling its function in exec statement.</p> <pre><code>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, '&lt;string&gt;', 'exec') exec (compiled, globals(), locals()) #in statement_module.__dict__ ajay.ajay_func() return ILessons_1(request); finally: __builtin__.__import__ = original_import pass </code></pre> <p>When I run this code I get error "global name 'ajay' is not defined"in line "return ILessons_1(request);". Interesting thing is python is able to resolve ajay in line just above this line. Im pretty sure Im making some mistake in exec statement but have not been able to figure out. </p> <p>Can some please help me solve this problem. Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload