简体   繁体   中英

Python Question about running multiple scripts in one script

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

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] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM