0
点赞
收藏
分享

微信扫一扫

PythonNote019--Python中main

勇敢乌龟 2022-08-04 阅读 44


介绍​​-if __name__ == '__main__'​​​的用法,Talk is cheap,Show me the code.
两个脚本:

file one.py

# 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

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

run one.py

top-level in one.py
one.py is

这里的逻辑很正常,调用脚本时,先输出print语句,然后​​__name__​​​是其本身,所以输出​​one.py is being run directly​

run 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

逻辑如下:

  1. import one时,print语句正常输出
  2. 当前模块名为two,所以​​__name__​​​不是​​one​​,输出one.py is being imported into another module
  3. 此时import one结束,two中的print正常输出​​top-level in two.py​
  4. 调用one模块中的func函数输出​​func() in one.py​
  5. 最后判断模块名,当前模块名为​​two​​​,所以输出​​two.py is being run directly​

Summary

简单总结下,如果是把脚本作为模块调用​​import​​​,则​​if __name__ == "__main__":​​​不运行,但是如果作为脚本直接运行,那么执行​​if __name__ == "__main__":​​后面的程序。

Ref

​​[1] https://www.zhihu.com/question/49136398/answer/114437881​​​ [2] ​​http://blog.konghy.cn/2017/04/24/python-entry-program/​​

                                     2018-03-25 于杭州


举报

相关推荐

0 条评论