if __name__ == "__main__" 的作用

作用:当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

例子:

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

如果你执行one.py文件,

python one.py
会输出:

top-level in one.py
one.py is being run directly
如果你执行two.py文件,

python 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

 总结:当模块导入时if __name__ == "__main__" 代码块不被执行,写if __name__ == "__main__"是为了防止模块导入,导致又重新运行了一遍导入的模块的代码。

posted @ 2019-04-11 20:05  LuoSpider  阅读(703)  评论(0编辑  收藏  举报