很多初学者会有这样的思考,通过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__
属性是否为__main__
的方式自我发现是否在main scope
中,这允许了一种在模块中条件执行代码的常见用法,当模块作为脚本或者使用python -m
命令运行时执行,而被导入时不执行。
当一个脚本从标准输入或者解释器提示行中被读取时,模块的__name__属性就会被设置为__main__。当模块通过import方式导入时,则__name__属性是模块的名称,不会修改为__main__。由此可以得出,若要启动一个应用程序在一个脚本中加入类似的语句即可。例子如下所示:
def test():
print('This is test method in com.richard.other')
def main():
test()
if __name__ == '__main__':
print('直接运行时,__name__属性:', __name__)
main()
else:
# 导入时被执行
print('导入时,__name__属性:', __name__)
要启动一个python语言编写的程序,程序入口脚本一定要包含"if __name__ == '__main__'":语句。if后面的else可以添加也可以不添加,添加的好处是对于模块的一些自测代码可以考虑添加进去,这样通过else分支就可以实现对模块的功能的测试。