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

Posted geeklove

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于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 modules 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.

 

以上是关于关于Python中的 if __name__ == '__main__'的主要内容,如果未能解决你的问题,请参考以下文章

Python中的构造“ if __name__ == '__main__'”

Python关于`if _name_ == “_main_“`

关于python的if __name__ == "__main__":

python3----如何简单地理解Python中的if __name__ == '__main__'

如何简单理解Python中的if __name__ == '__main__':

如何简单地理解Python中的if __name__ == '__main__'