Why do you write if __name__ == "__main__"?

Asked 2 years ago, Updated 2 years ago, 44 views

In the code below, Why do you write if__name__=="__main_"?

if __name__ == ""__main__""
    print ""hello""

python

2022-09-22 22:38

1 Answers

When the script is run after being parsed by the Python interpreter command (for example, python myscript.py) Unlike other languages, Python does not have a main function that runs automatically. Python executes all unindented codes (level 0 code) instead of having a main function However, a function or class is defined, but not executed

If you ask, the top code is the if block, and _name___ is the built-in variable that contains the name of the current module. _name___ is set to "_main__" only if this module runs directly, such as python myscript.py.

Therefore, if the interrogator's code is imported by another module, the definition of the function and the object is imported, but the if statement is not executed because __name__ is not _main__".

Like this,

if __name__ == "__main__":

You can use to test whether the script runs directly or imported.

For example, for the following code,

def func():
    print("function A.py")

print("top-level A.py")

if __name__ == "__main__":
    print("Run A.py Directly")
else:
    print ("A.py is imported and used")
import A as one

print(""top-level in B.py"")
one.func()

if __name__ == "__main__":
    print("Directly executed by B.py")
else:
    print ("B.py is imported and used")
>> python A.py
top-level in A.py
Run directly by A.py


>>python B.py
top-level in A.py
A.py imported and used
top-level in B.py
function A.py
Run directly by B.py


2022-09-22 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.