I can put an import statement in a string, exec it, and it works (prints a random digit):
code = \"\"\" import random def f(): print random.randint(0,9)
Specify that you want the global random module
random
code = """ import random def f(): global random print random.randint(0,9) """
The problem here is that you're importing the random module into your function scope, not the global scope.