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

From: Irmen de Jong (
Date: 11/27/03

Date: Thu, 27 Nov 2003 21:59:25 +0100

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)



Relevant Pages

  • Re: del an imported Class at EOF... why?
    ... I've just inherited a large amount of python code. ... a desire to prevent people importing his module and then using the ... from alienmodule import AlienClass ... del AlienClass ...
  • Re: globally available objects
    ... > I would like to create an object while importing a module only the ... > first time it get's imported. ... From the viewpoint of Python code, ... the name indicated -- either its default 'fetch' name or the 'as' name. ...
  • Re: suppressing import errors
    ... As with any Python code, you can wrap the import into a try: ... import badModule ... Is there a way to suppress all the errors when importing a module in python? ...
  • Re: semi-newbie module namespace confusion
    ... running a piece of python code as a script isn't the same thing as ... "If you run a module as a script (i.e. give its name to the inter- ... preter, rather than importing it), it's loaded under the module ...