Im trying to import a module using exec statement
Don't do that.
First, do you really need to import a module programmatically? If you tell us what you're actually trying to accomplish, I'm willing to bet we can find the square hole for your square page, instead of teaching you how to force it into a round hole.
If you do ever need to do this, use the imp
module; that's what it's for.
Especially if you want to import a module by path instead of by module name, which is impossible to do with the import
statement (and exec
isn't going to help you with that).
Here's an example:
import imp
def test(jobname):
print jobname
while open(jobname, 'r') as f:
job = imp.load_module('test', f, jobname, ('.py', 'U', 1))
Of course this doesn't do the same thing that import test1
would do if it were on your sys.path
. The module will be at sys.modules['test']
instead of sys.modules['test1']
, and in local variable job
instead of global variable test1
, and it'll reload instead of doing nothing if you've already loaded it. But anyone who has a good reason for doing this kind of thing had better know how to deal with all of those issues.