![e7f0b3ab4acd0def73faa9249f1da574.png](https://i-blog.csdnimg.cn/blog_migrate/ca8f7506281750e58af1535ba7f6327a.jpeg)
在Python模块当中,通常会写上一行“if __name__==’__main__:”作为程序的入口,但似乎没有这么一行代码,程序也能正常运行。那么这句代码是多余的吗,为什么?
Python模块通常有两种运行方式,如下:
- 第一种:作为模块直接运行。
- 第二种:被导入( import )到其他的 Python 模块中。
if __name__==’__main__: 的作用就是控制这两种情况代码执行过程,即在if __name__==’__main__: 下的代码只有在第一种情况下才会被执行,而当该模块被导入(import ) 到其他模块时,if __name__==’__main__: 下的代码是不会被执行的。
简单讲,if __name__==’__main__: 让你写的模块既可以导入到其他模块中用,也可以直接使用。下面我们通过实例详细介绍说明。
作为模块直接运行
![f42b977bb90f9619d6d43c7544c916d8.png](https://i-blog.csdnimg.cn/blog_migrate/d259290165ea745b03c0364d737b8ba6.jpeg)
如下,直接执行p_testops.py模块 ,我们可以看到if __name__==’__main__: 语句之前和之后的代码都被执行。
![97e026cce15154d23967f53a7ce227ee.png](https://i-blog.csdnimg.cn/blog_migrate/a1a973a40609d4b4f517d350b5e5f355.jpeg)
被导入(import)到其他模块
![3141badcc307c661d2bb6eaa1d1265a6.png](https://i-blog.csdnimg.cn/blog_migrate/bc25503f142c6ee5d9d04b0045159ce9.jpeg)
如下,当执行 import testops 时,只输出了print testops.format_time() 的运行结果。即,if __name__==’__main__:之前的语句被执行,之后的没有被执行。
![983f16ccffde57e1cabe1d1874f990cf.png](https://i-blog.csdnimg.cn/blog_migrate/32a49116d7926e9c051a7df3f377c336.jpeg)
if __name__ == '__main__':运行原理
既然是个 if 判断语句,我们就来看看__name__ 。
__name__是标识模块的名字的一个系统变量,上面例子中提到的n_testops.py、p_testops.py就是两个模块,我们在文中开头提到模块运行分两种情况,如下。
作为模块直接运行
假如当前模块是主模块(直接运行),那么此模块名字就是__main__,通过if判断__name__==’__main__结果为真,这样就可以执行if __name__ == '__main__'后面的代码。示例代码如下:
![8c7a4d793ff5544bfd2d170ed98f6466.png](https://i-blog.csdnimg.cn/blog_migrate/6bbae6f05e8140f09db64222ad711962.jpeg)
如下,可以看到p_testops.py被直接运行时,__name__的值为__main__,那么__name__=="__main__"为真,因此执行了 print testops.str_time()。
![f6c5632e11ae5594aabd4b3095ab5282.png](https://i-blog.csdnimg.cn/blog_migrate/9a08236e13bfd8c2138f14b3978fbd40.jpeg)
导入(import)到其他模块
假如此模块是被导入(import)的,则此模块名字为文件名字(不含后缀),通过if判断__name__=="__main__"为假,这样就会跳过if __name__ == '__main__': 后面的代码。示例代码如下:
![1e907cb1d4ddb1b691e27bfa5e0e2a3f.png](https://i-blog.csdnimg.cn/blog_migrate/689077adc9bf235e2de1168b27f104c1.jpeg)
如下,我们可以看到 p_testops.py模块被导入到n_testops.py模块中,__name__的值为p_testops,__name__=="__main__"为假,跳过if __name__ == '__main__':后面的代码。
![f37541757a43be82a4545e7d36630cec.png](https://i-blog.csdnimg.cn/blog_migrate/16815d7f4ce538637556c8c33cbafa3b.jpeg)
![1cd17555623dc6ebe90b36f9d363a291.png](https://i-blog.csdnimg.cn/blog_migrate/f2805a7822d6b339902ca70374955a61.jpeg)