Problem with exec

Justus Schwabedal justus.schwabedal at gmx.de
Thu Mar 13 18:47:58 EDT 2008


I'm trying to parallise with python. Specifically I'm sending code to  
the processes and let them exec this code (in ascii form). However I  
ran into a problem with Namespaces (I think) which I do not understand.

Here's what I do first:
---------------------------------------
bash-3.2$ cat execBug.py
#! /usr/bin/python
header="""
from scipy import randn
def f():
         return randn()
"""
exec header
print "f() =",f()

bash-3.2$ ./execBug.py
f() = 0.633306324515


it est: it works.
However when I do this:

bash-3.2$ cat execBug2.py
#! /usr/bin/python
header="""
from scipy import randn
def f():
         return randn()
"""
def g():
         exec header
         return f()
print "g() =",g()
bash-3.2$ ./execBug2.py
g() =
Traceback (most recent call last):
   File "./execBug2.py", line 10, in <module>
     print "g() =",g()
   File "./execBug2.py", line 9, in g
     return f()
   File "<string>", line 4, in f
NameError: global name 'randn' is not defined
bash-3.2$ ???

I get this global name error. I can fix it with adding some line like  
"global randn" but I don't want to do this. I want to do exactly what  
I wrote: Import the function scipy.randn in the local namespace of the  
function "g" so that "return f()" makes sense. Can anybody help me out?
Yours Justus



More information about the Python-list mailing list