根据exec_documentation:
If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.
内部方法globals()和locals()是不同的对象:
def method():
print(globals() == locals())
exec('X=10')
print('Method execution =', X)
method()
输出:
False
NameError: name 'X' is not defined
在全局级别上,这些对象相等:
print(globals() == locals())
exec('X=99')
print('Global exec =', X)
输出:
True
Global exec = 99
因此,如果要通过方法执行此操作,则需要将同一对象传递给exec.对于您的代码,它看起来像这样:
def func_call(filename):
exec(open(filename).read(), globals(), globals())
print("X = %s" %X)
func_call("./init.py")
但是,正如我在评论中提到的那样,使用const创建文件并将其导入.除非您百分百确定自己在做什么,否则请尽量避免不惜一切代价使用exec / eval.