《简明Python教程》
http://stackoverflow.com/questions/419163/what-does-if-name-main-do
每个模块都有名字,在模块中可以通过__name__
来找出模块的名称。if __name__ == "__main__
可以做到在程序本身被使用时运行主块,而在它被别的模块输入(import)时不运行。
#using__name__
if __name__ == 'main':
print('this program is being run by itself')
else:
print('it is imported from other module')
$python using__name__.py
this program is being run by itself
$python
>>> import using__name__
it is imported from other module
如果这个文件从其他module中import过来,__name__会被设置成module的名字。
通过if __name__ == 'main'
,你可以只执行这些代码当你想把这个模块当成程序运行并且可以不让代码运行当别人只是想import你的模块并且把它当成函数调用。