A: 

This has probably to do with how 'from x import *' works. If you call this from 'top-level', it gets imported into globals() for the whole module.

However, if you call this inside a function, it gets imported only into locals() - in the function. The exec() gets evaluated inside a function in caller2; therefore the import * doesn't get into globals() and the 'inner' main function doesn't see it.

BTW: it is intersting that if you try code like this:

def run():
    from time import *
    def test():
        print time()
    test()
run()

You will get an exception: SyntaxError: import * is not allowed in function 'run' because it is contains a nested function with free variables

But that is precisely what you are doing with the exec, but it somehow surprisingly sneaks through.

However - considering the other answer here - why don't you use something other instead? Look at the 'imp' module documentation - in particular functions find_module and load_module.

ondra
+1  A: 

Here's an idea: don't use exec. Basically every time I've seen someone use exec or eval it's because they don't know that a better way to accomplish the same thing already exists; it's a crutch that hinders writing dynamic code, not a way to write code that's somehow more dynamic.

Aaron Gallagher