Im trying to import a module using exec statement but it fails,
code.py
def test(jobname):
print jobname
exec ('import ' + jobname)
if __name__ = '__main__':
test('c:/python27/test1.py')
Error: Syntax error:
import:c:\python27 est1.py
Im trying to import a module using exec statement but it fails,
code.py
def test(jobname):
print jobname
exec ('import ' + jobname)
if __name__ = '__main__':
test('c:/python27/test1.py')
Error: Syntax error:
import:c:\python27 est1.py
You probably mean execfile(jobname). And import does not work with filenames. It works with package names. Any good tutorial would cover that. Another issue would be the \t being interpreted as a tab character, but here it is not the case because you are uaing forward slash not baclslash...
Somehow, I think you must be calling
test('c:\python27\test1.py')
instead of
test('c:/python27/test1.py')
The backslash in front of the t is being interpreted as a tab character. Thus the error
import:c:\python27 est1.py
Notice the missing t.
Secondly, the import command expects a module name, not a path. For importing, use __import__ not exec or execfile. execfile has been removed from Python3, so for future compatibilty, you may not want to use it in Python2. exec can be used instead, but there are problems with using exec.
Assuming c:\python27 is in your PYTHONPATH, you could
do something like this:
def test(jobname):
print jobname
__import__(jobname)
if __name__ == '__main__':
test('test1')
def test(jobname):
print jobname
a = jobname.split('/')
b = "/".join(a[0:-1])
c = a[-1][0:-3]
sys.path.append(b)
exec ('import ' + c)
if __name__ = '__main__':
test('c:/python27/test1.py')
Try this code. Your path must be added to sys.path() variable.
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.