On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > Hello > > I am completely puzzled why the following exec code does not work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > def execute(): > exec mycode > execute() > > > I get the error: > > [EMAIL PROTECTED]:/opt/qbase# python error1.py > Traceback (most recent call last): > File "error1.py", line 5, in ? > execute() > File "error1.py", line 4, in execute > exec mycode > File "<string>", line 4, in ? > File "<string>", line 3, in f > NameError: global name 'math' is not defined
This is due to a namespace issue with exec, see http://docs.python.org/ref/exec.html#l2h-569 The namespace used in an exec statement is the local scope. This scope is different in your two cases. If you change the exec call to def execute(): exec mycode in globals() It will work as you expect. Note that the following code _does_ work: > > mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" > exec mycode > > > I have tested this in python 2.3 and 2.4. > > > Regards > Carl > > -- > http://mail.python.org/mailman/listinfo/python-list >
-- http://mail.python.org/mailman/listinfo/python-list