if __name__ == '__main__'

__name__ == '__main__'

# /home/main_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")
# /home/main_two.py
import main_one

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

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

运行main_one.py,输出

top-level in one.py
one.py is being run directly

运行main_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

我的理解

当一个A脚本被执行时,这时A脚本的__name__ "__main__)"就相等

当在B脚本导入A脚本,B脚本执行时,这时A脚本的__name__ "__main__)"就不相等

关于main_two.py执行的问题

对导入的模块来说,模块中的函数是调用时才执行的,但是语句会立刻执行(那些没有缩进的语句)

参考知乎

posted @ 2020-08-07 22:58  榕霖  阅读(153)  评论(0编辑  收藏  举报