3

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.

3

1 Answer 1

5

According to exec_documentation:

If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

Inside method globals() and locals() are different objects:

def method():
    print(globals() == locals())
    exec('X=10')
    print('Method execution =', X)

method()

output:

False
NameError: name 'X' is not defined

In global level this objects are equal:

print(globals() == locals())
exec('X=99')
print('Global exec =', X)

Output:

True
Global exec = 99

So If you want to do it via method, you need to pass the same object to exec. For your code it would look like this:

def func_call(filename):
  exec(open(filename).read(), globals(), globals())
  print("X = %s" %X)

func_call("./init.py")

Nevertheless, as I mentioned in comment, create file with consts and import it. Try to avoid using exec/eval at all costs, unless you are 100% sure what you are doing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.