Python中if __name__ == '__main__' 的用法

来源:互联网 发布:知乎 了不起的盖茨比 编辑:程序博客网 时间:2024/06/01 20:44

Python中if __name__ == '__main__'的用法


当脚本通过命令的形式给出

python myscript.py

所有在0层缩进(indentation level )的代码将会执行,class和function将不会执行。不像其他语言,Python中无自动运行的main()函数;主函数隐含在所有0层缩进的代码。
__name__是Python的内建函数,指的是当前模块的名称,在脚本被直接执行时__name__被替代为__main__,因此可以用这种办法测试代码是否被直接执行。
下面是一个例子:

# file one.pydef 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.pyimport one#注意这导入了one.pyprint("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.pyone.py is being run directly

如果你执行two.py

python two.py

结果为:

top-level in one.pyone.py is being imported into another moduletop-level in two.pyfunc() in one.pytwo.py is being run directly

文章转载翻译至stackoverflow中Adam Rosenfield的回答