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"?

3
  • Yes, Python will interpret the scripts on import. The typical way of avoiding this is using if __name__ == "__main__": See this or this for instance. Commented Dec 13, 2022 at 20:10
  • A module is defined by executing the code in a file. Commented Dec 13, 2022 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? Commented Dec 13, 2022 at 21:32

1 Answer 1

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] 
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.