使用execfile运行带有闭包的脚本时,未定义全局名称

时间:2018-04-02 21:27:47

标签: python python-2.x execfile

我正在尝试使用script2script1运行execfilescript2包含闭包:

  

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不可能,那么该怎么办?

1 个答案:

答案 0 :(得分:-1)

MyVar2 = 'value2'

def fun1():
    global MyVar2
    print(MyVar2)

fun1()

修复需要在脚本2中完成。