一句经典介绍if name==’main‘功能的描述为:“Make a script both importable and executable”
表示可以让脚本模块不仅能够被其他模块调用,还能在当前文件中运行模块。如果直接作为脚本运行,则运行if name==’main‘后的代码,如果被其他模块调用,则不运行if name==’main‘后的代码。这个功能可以提供一个很好的代码调试方法,我们可以将对这个模块的调试代码写到if name==’main‘中,当该模块被调用的时候并不会运行调试程序。
例:
#test.py文件
def distest():
print('this is %s',__name__)
if __name__ == '__main__':
distest()
print('in the function if')
如果单独运行上述代码则结果为:
this is %s __main__
in the function if
如果用一下代码调用test.py的模块
#test_import.py文件
from test import distest
distest()
运行结果如下,没有运行if函数中的内容。
this is %s test
原理:每个python模块(test.py或test_import.py)都包含了name变量,当该模块直接作为脚本运行时,name等于该模块的文件名(包含.py,例如test.py),当该模块被import调用时,则在被调用文件中name等于被调用模块名称(不包含.py,例如test),而main等于当前执行文件的名称(包含.py,例如test_import.py)。