Generated code that is exec-ed (to simulate import) cannot import os.path??

Irmen de Jong irmen at
Thu Nov 27 21:59:25 CET 2003

I don't understand why the following doesn't work.
What I want to do is dynamically import some generated
Python code and I'm doing this using compile and exec'ing
it in the dict of a new empty module object.
That works okay, but as soon as the generated code
tries do perform certain imports, it fails!
Certain other imports succeed. Consider this example code:

import imp

print 'importing random'
import random
print 'importing os'
import os
print 'bye!'

def getName():
     return 'Hello there'

newmod = imp.new_module('generated.testmodule')
code=compile(source,'<generated code>','exec')
print 'got code...'
exec code in newmod.__dict__		
print 'done, newmod.getname(): ',newmod.getName()

When run, it produces the following output:

got code...
importing random
importing os
Traceback (most recent call last):
   File "", line 17, in ?
     exec code in newmod.__dict__
   File "<generated code>", line 5, in ?
   File "C:\Python23\lib\", line 131, in ?
     from os.path import curdir, pardir, sep, pathsep, defpath, extsep, altsep
ImportError: No module named path

What's going on? Why can't it find os.path?

(Python 2.3.2, tested on linux and windows)



More information about the Python-list mailing list