很多初学者会有这样的思考,通过python编写代码,如何启动一个python编写的应用程序呢?
有过c/c++开发的朋友都知道:c/c++程序都会有一个main函数作为程序的入口函数。python是c语言开发的,作为更高级的语言,肯定是也是参考c/c++的方式来启动程序。谈到这里就不能绕过__main__。
对__main__的英文介绍如下:
'_main_' is the name of the scope in which top-level code executes. A module’s _name_ is set equal to '_main_' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own _name_, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
中文含义是如下:
__main__
是顶层代码执行环境的名字。当一个模块从标准输入,脚本或者解释器提示行中被读取时,模块的__name__
属性被设置成__main__
。
模块可以依据检查__name__
属性是