【发布时间】:2017-12-06 20:35:07
【问题描述】:
我需要在 python shell 中执行一个文件。
我可以
exec(open('Test.py').read())
但我需要从函数内部调用它。
“Test.py”将设置变量C=10
所以,
#x.py
def load(file):
exec(open(file).read(),globals())
>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined
我已经传入了全局变量,但我仍然无法从 exec 访问变量。 参考资料:
In Python, why doesn't an import in an exec in a function work?
【问题讨论】:
-
execfile("filepath") -
因为你我不能重现这个...
-
提一下Python3.6会很有帮助。 'execfile' 不起作用