0

I am trying to code a "parent" py file that can execute multiple py files on it.
The structure is like the follow if i simplify.

parent.py
  - childeren1.py

And inside the parent.py it executes children1.py in this way.

**parent.py**

a = 0
with open ("children1.py", "r", encoding="utf-8") as file:
    exec(file.read())
file.close()
print(a)

Inside the "children1.py",

**children1.py**

a = 1

If I run parent.py, it returns a=1 which is the result from the children1.py
I want it to be a=0 though.

Can I clear the variable that is used in the children1.py after its execution has finished whatever the variable was in exec()?
I want the variables in parent.py to be absolute.

2
  • Is there any reason to do this instead of import? Even a weird importlib import seems like it would make more sense Commented Feb 25, 2020 at 14:20
  • @CJR I have a lot of py files to execute, so it is hard to type every single py file name as the import file Commented Feb 25, 2020 at 21:28

1 Answer 1

1

Take a look at the documentation. You can see that the exec function has two optional arguments. The documentation says "if the optional parts are omitted, the code is executed in the current scope". So, the variable a in your children1.py file is just the same variable as the a in parent.py.

If you do not want this behavior, you have to set some dictionaries for the global and/or local variables. For example, choosing an empty dictionary changes parent.py to

with open ("test2.py", "r", encoding="utf-8") as file:
    exec(file.read(), {})
file.close()
print(a)

Then, the value of a is zero at the end of the program.

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.