关于Python中的 if __name__ == '__main__'

官方文档对于"__main__"的回答(ref: https://docs.python.org/2/library/__main__.html):

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:
if __name__ == "__main__":
    main()

也就是说,当解释器的主项目执行的时候,使用__main__来指示代码的执行范围。执行主项目的命令可以来自标准输入(python xxx.py),脚本文件等

stackoverflow的回答如下(ref:https://stackoverflow.com/questions/419163/what-does-if-name-main-do):

对于__name__的解释:

For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

为什么要这样设计的原因:

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

猜你喜欢

转载自www.cnblogs.com/geeklove01/p/9045530.html