I'm having an issue with running a python script in a python script that i simply do not understand:
Assume we have 2 files in the same directory: 'init.py' and 'text.py'
init.py:
X = 5
print("init.py was run")
test.py:
exec(open("./init.py").read())
print("X = %s" %X)
If I run test.py now, I get
init.py was run
X = 5
However, if I change test.py into:
def func_call( filename):
exec(open(filename).read())
print("X = %s" %X)
func_call("./init.py")
I get:
init.py was run
Traceback (most recent call last):
File "test.py", line 5, in
func_call("./init.py")
File "test.py", line 3, in func_call
print("X = %s" %X)
NameError: name 'X' is not defined
Can someone explain to me why this leads to different results? Is there a workaround for this? My goal is to initializes most of my variables by running a python script and accessing the variables set up in that python script.