Python中if __name__ == '__main__'
的用法
当脚本通过命令的形式给出
python myscript.py
所有在0层缩进(indentation level )的代码将会执行,class和function将不会执行。不像其他语言,Python中无自动运行的main()函数;主函数隐含在所有0层缩进的代码。
__name__
是Python的内建函数,指的是当前模块的名称,在脚本被直接执行时__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#注意这导入了one.py
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