我正在尝试使用script2
从script1
运行execfile
,script2
包含闭包:
script1.py
MyVar1 = 'value1'
def fun1():
print(MyVar1)
def fun2():
execfile('script2.py')
fun1()
fun2()
script2.py
MyVar2 = 'value2'
def fun1():
print(MyVar2)
fun1()
发生错误
File "...script1.py", line 12, in <module>
fun2()
File "...script1.py", line 9, in fun2
execfile('script2.py')
File "script2.py", line 8, in <module>
fun1()
File "script2.py", line 5, in fun1
print(MyVar2)
NameError: global name 'MyVar2' is not defined
如何修复script1
仍在使用execfile
?
更新
如果execfile
不可能,那么该怎么办?
答案 0 :(得分:-1)
MyVar2 = 'value2'
def fun1():
global MyVar2
print(MyVar2)
fun1()
修复需要在脚本2中完成。