经典的英文解释:Make a script both importable and executable
中文解释:使脚本可以被调用import并且也可以直接运行
1、直接运行
# cat test_fun.pydef fun(): print(__name__) print('this is fun')if __name__ == '__main__': fun() print('this is main') python test_fun.py__main__this is funthis is main2、被调用import
>>> import test_fun>>> test_fun.fun()test_funthis is fun调用导入时:此处输出没有显示”main“,也就是说模块name = ‘main’ 下面的代码并未执行,main函数没有执行。
这个功能还有一个用处:调试代码的时候,在”if name == ‘main‘“中加入一些我们的调试代码,我们可以让外部模块调用的时候不执行我们的调试代码,但是如果我们想排查问题的时候,直接执行该模块文件,调试代码能够正常运行!