1

I have been trying to figure out how to call a second script and get it to run before continuing on with my current one.

I have my first script (file1.py) which defines a string called PATH_DATA. The second script (file2.py) imports PATH_DATA using:

from file1 import PATH_DATA

Then runs some functions and outputs data to a new filepath. Then the first script should continue, defining the new file path PATH_DATA_2.

I am currently trying to acheive this using:

exec(open('file2.py').read())

which works fine for the most part. The problem is the entire script (file1) seems to be running twice all the way through, instead of once. Is there a fix to this? or a better way for me to achieve the end result? (I am using Python 3).

Thanks!

asked Jun 28, 2018 at 10:19

1 Answer 1

1

If you want to continue using your current workflow, wrap anything with side effects in file1 like this, and define the variable you want to import outside of it.

PATH_DATA = "your/path"
if __name__ == "__main__":
 print("do stuff with side effects")

The stuff under "if name equals main" is not run when file1 is imported.

I would personally just import a function that wraps the functionality from file2 into file1 and pass it the path as an argument though. Seems more explicit and simple.

answered Jun 28, 2018 at 10:29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.