Python中if __name__ =="__main__":的作用

       在很多Python代码中,最后的部分会执行一个判断语句(注意__name__中下划线的长度,它表示:两根下划线+name+两根下划线)

if __name__== '__main__':

那么这个判断的代码是什么意思?

       在Python编译器读取源文件的时候会执行它找到的所有代码,而在执行之前会根据当前运行的模块是否为主程序而定义变量__name__的值是__main__还是模块名。因此,该判断语句为真的时候,说明当前运行的脚本为主程序,而非主程序所引用的一个模块。当你想要运行一些只有在模块当做程序运行时,只要将代码放在 if __name__=="__main__": 判断语句之后就可以了。

举例说明:

file_one.py文件

#下面一行为环境变量,指明python.exe的目录
#!C:\Program Files\Python\python.exe
# -*- coding: UTF-8 -*-

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

运行结果:

"C:\Program Files\Python\python.exe" E:/python_phcharm/file_one.py
top-level in one.py
one.py is being run directly

file_two.py文件

#下面一行为环境变量,指明python.exe的目录
#!C:\Program Files\Python\python.exe
# -*- coding: UTF-8 -*-
import file_one              #start executing one.py

print("top-level in two.py")
file_one.func()

if __name__=="__main__":
    print("two.py is being run directly")
else:
    print("two.py is being import into another module")

运行结果:

"C:\Program Files\Python\python.exe" E:/python_phcharm/file_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
发布了39 篇原创文章 · 获赞 8 · 访问量 9197

猜你喜欢

转载自blog.csdn.net/cxd3341/article/details/100106132