简体   繁体   中英

How do I access variables from another file in Python without running all the code outside of the variable declaration?

I have looked up a couple of solutions to this problem, but none of them seem to work. Lets just say I have a file named "Var", where I simply put:

myvar = 25
print("myvar is equivalent to 25.")

And then I have another file called "Run", where I put:

from Var import myvar
print(myvar)

From the "Run" file, the only thing I want to access from that file is the variable, but when I actually run the code, it runs the entire file, so the output is:

myvar is equivalent to 25.
25

All I want to do is access the variable but for some reason it is running the entire file! How do I get it so that it only gets the variable and doesn't run the entire file?

When a python module is loaded it will go through the file and execute all of the statements on the top level.

If you want the print statement to only happen if you execute the file as a script (say by running python Var.py ) then you need to check if it is the "main" module.

To do so you can check the __name__ attribute.

For Var.py

myvar = 25


if __name__ == "__main__":
    print("myvar is equivalent to 25.")

For Run.py :

from Var import myvar


if __name__ == "__main__":
    print(myvar)

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