How to understand if __name__ == '__main__' correctly?

Author: Zhihu User
Link : https://www.zhihu.com/question/49136398/answer/114437881
Source: Zhihu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

# file one.py
def func():
    print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module") # file two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else: print("two.py is being imported into another module") 

If you execute one.py file,

python one.py

will output:

top-level in one.py
one.py is being run directly

If you execute the two.py file,

python two.py

will output:

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.

I won't translate it. First of all, my translation is ugly. Second, I think English is easier to understand. . .

It is used as above.

Then I think its function is to make if __name__ == '__main__' the code behind it not execute . Will the code run more concisely and smoothly? ? ? Because you only need to use the part you want to use. . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325142058&siteId=291194637