python exec behaves inconsistent with respect to module imports
carl.dhalluin at gmail.com
carl.dhalluin at gmail.com
Wed Sep 5 09:12:24 EDT 2007
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:
root at devmachine1:/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
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
More information about the Python-list
mailing list