介绍-if __name__ == '__main__'的用法,Talk is cheap,Show me the code.
 两个脚本:
file one.py
# file one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
file two.py
# file two.py
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
run one.py
top-level in one.py
one.py is
这里的逻辑很正常,调用脚本时,先输出print语句,然后__name__是其本身,所以输出one.py is being run directly
run two.py
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
逻辑如下:
- import one时,print语句正常输出
 - 当前模块名为two,所以
__name__不是one,输出one.py is being imported into another module - 此时import one结束,two中的print正常输出
top-level in two.py - 调用one模块中的func函数输出
func() in one.py - 最后判断模块名,当前模块名为
two,所以输出two.py is being run directly 
Summary
简单总结下,如果是把脚本作为模块调用import,则if __name__ == "__main__":不运行,但是如果作为脚本直接运行,那么执行if __name__ == "__main__":后面的程序。
Ref
[1] https://www.zhihu.com/question/49136398/answer/114437881 [2] http://blog.konghy.cn/2017/04/24/python-entry-program/
2018-03-25 于杭州
                










