Plota
Plota

Reputation: 66

Running a second python script before continuing with the first

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!

Upvotes: 1

Views: 248

Answers (1)

fordy
fordy

Reputation: 2701

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.

Upvotes: 1

Related Questions