I am trying to create my own application like python interpreter. I use the exec statement (in Python 2.7.6) to execute the given code, but global variables do not work as expected. Can someone explain why this is not working:
def print_x():
print(x)
g = {'x': 10, 'print_x': print_x}
l = {}
exec('print_x()', g, l)
The result (whether the print_x function is in g or l) is an error:
NameError: global name 'x' is not defined
So, are the global variables executed for exec not transferred to the called functions?
source
share