我有一些使用exec()的python(2.7)代码:
import math
def some_function(a, b):
return a+b
safe_dict = { 'Sqrt': math.sqrt, 'Smurf': some_function, "__builtins__": None }
with open('my_file.py') as f:
exec(f.read(), safe_dict, {})
print('The End')
“ my_file.py”是: 打印(“在执行脚本中”)
print('sqrt(2) = %f' % Sqrt(2)) # Call to math.sqrt through name 'Sqrt' given in globals
print('3+4 = %d' % Smurf(3, 4)) # Call to some_function through name 'Smurf' given in globals
def my_func(x):
return Sqrt(2+x)
print("my_func: %f" % my_func(1)) # No problems
def my_func2(x, f):
return f(x-1)
print("my_func2: %f" % my_func2(5, my_func)) # No problems too
def my_func3(x):
return my_func(x-1) # Here, leads to a "NameError: global name 'my_func' is not defined" in the next line
print("my_func3: %f" % my_func3(5))
我不明白为什么在尝试调用my_func时my_func3中出现NameError。
为什么my_func3即使先前已定义也无法调用my_func?
有没有办法使其工作(不是在主模块中定义的my_func)?
修改 错误是:
Traceback (most recent call last):
File "main.py", line 9, in <module>
exec(f.read(), safe_dict, {})
File "<string>", line 16, in <module>
File "<string>", line 15, in my_func3
NameError: global name 'my_func' is not defined