【3.9】if name == "main"

一般来说,我们希望写的python文件既可以自己运行,也可以作为模块来被其他程序调用。那么问题来了,如果自己本身就能运行,那么被调用的时候,是否会运行一次呢?这个时候if __name__ == "__main__" 就发挥其牛逼的作用了。

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special **name** variable to have a value "**main**". If this file is being imported from another module, **name** will be set to the module's name.

每一个模块(py文件)都有个默认的name参数,这个参数默认值为main;

只有在被其他模块A(py文件)调用的时候,这个被调用模块B的name发生了改变,改变成了A的文件(模块)名;

也就是说,如果是外部引用一个模块,那么该模块的 if __name__== "main" 中的语句将不会运行。

因此python就通过 __name__ 来达到检测模块的设计意图。在测试该模块时,执行用于测试的代码。在被导入时,不执行这些测试代码。

#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
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")

 python one.py

The output will be:

top-level in one.py
 one.py is being run directly
 If you run two.py instead:
	
 python two.py

The output will be:

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

参考资料:

http://stackoverflow.com/questions/419163/what-does-if-name-main-do

http://my.oschina.net/leonwong1121/blog/225438

http://bbs.csdn.net/topics/320265093

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn