If that code is being imported into another module, the various function and class definitions will be imported, but the main() code won't get run. As a basic example, consider the following two scripts:
# 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")Now, if you invoke the interpreter as
python one.pyThe output will be
top-level in one.py one.py is being run directlyIf you run two.py instead:
python two.pyYou get
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 directlyThus, when module one gets loaded, its __name__ equals "one" instead of __main__.
####原文地址: http://stackoverflow.com/questions/419163/what-does-if-name-main-do
一个非常重要的应用是,if __name__=="__main__":
条件下的代码,再被import到其他py文件中时,是不会被执行的。。这点非常的好,
可以让子py文件完整测试,或演示。又不影响被调用方。。
