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!
1 Answer 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.