0

I have couple questions regarding running code from multiple files from one .py file

When I import the Files with

from [subfolder] import [First scriptname - without .py] 
from [subfolder] import [Second scriptname - without .py] 

the scripts start running instantly, like if my scripts have a print code it would look like this after running the combined-scripts file

print("Hi Im Script One") 
print("Hi Im Script Two")

now I could put them in functions and run the functions but my files also have some variables that are not inside functions, the question I have is if there is a way to not start the script automatically after import?

Also what happens with variables inside these scripts, are they usable throughout the combined file or do i need to state them with something like "global"?

Adam Smooch
  • 1,167
  • 1
  • 12
  • 27
PRR
  • 13
  • 4
  • Yes, Python will interpret the scripts on import. The typical way of avoiding this is using `if __name__ == "__main__":` See [this](https://stackoverflow.com/q/419163) or [this](https://realpython.com/if-name-main-python/) for instance. – Savir Dec 13 '22 at 20:10
  • A module is defined by executing the code in a file. – chepner Dec 13 '22 at 20:13
  • so i put the ` if __name__ == "__main": ` code on top of the variables of the ** original imported script ** and then it will only run when i trigger something for that script to run? – PRR Dec 13 '22 at 21:32

1 Answers1

1

is there a way to not start the script automaticly after import?

This is what python's if __name__ == "__main__": is for.

Anything outside that (imports, etc.) will be run when the .py file is imported.

what happens with variables inside these scripts, are they usable troughout the combined file or do i need to state them with something like "global"?

They may be best put inside a class, or you can also (not sure how Pythonic/not this is):

from [FirstScriptName_without_.py] import [className_a], [functionName_b], [varName_c] 
Adam Smooch
  • 1,167
  • 1
  • 12
  • 27