-1

I am trying to run script2 from script1 with execfile and script2 contains closures:

script1.py

MyVar1 = 'value1'


def fun1():
    print(MyVar1)


def fun2():
    execfile('script2.py')

fun1()
fun2()

script2.py

MyVar2 = 'value2'


def fun1():
    print(MyVar2)


fun1()

An error occurs

  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

How to fix script1 still using execfile?

UPDATE

If it is impossible with execfile then how to do otherwise?

Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

-1
MyVar2 = 'value2'

def fun1():
    global MyVar2
    print(MyVar2)

fun1()

The fix needs to be done in script 2 actually.

Paandittya
  • 885
  • 8
  • 17
  • Downvoter. Please educate me thats wrong in my understanding? – Paandittya Apr 02 '18 at 22:16
  • `fun1` isn't going to look for a local `MyVar2` anyway, since `fun1` contains no assignments to `MyVar2`. – user2357112 Apr 02 '18 at 22:18
  • The problem is in how `execfile` almost-but-not-really executes the contents of `script2.py` in the local namespace of `fun2` from `script1`. – user2357112 Apr 02 '18 at 22:20
  • Ok. That makes sense. Thanks for correcting my understanding abt this. Edited the ans to exclude the wrong explanation. Sorry for that. – Paandittya Apr 02 '18 at 22:24